Cloudbook: C

  1. Home
  2. Variables
  3. Modeling
  4. § 3 exercise →
Scope

The essential properties of a variables are its type, scope and lifetime. No program can be correct if these properties are not understood and controlled for each and every variable.

The scope of a variable is the region on the text in which that variable name is known. It is possible that a program has multiple variables by the same name. Scoping rules disambiguate which variable is being referred to.

Consider a snippet of C code:

        	int f(int i) {
        		return (i<0)?-i:i ;
        	}
        
This is a function whose computed value is simply the absolute value of the argument value.

Type: The variable i in this example has type int, one the integer types including char, short, int, long and long long, in signed and unsigned versions, that have values similar to mathematical integers, except they are of limited range.

Scope: A variable can be referred to by its name, but the same name can refer to several different variables. A context is required to disambiguate the reference from among similarly named variables. This context is called the scope, and at most one variable of a given name is in scope at any point in the written code.

The variable i in this example has function scope: unless otherwise hidden by a redeclaration, references to i in the body of the function f refer to this variable, whereas variables with the name i outside this function refere to some other variable.

    	{
    		int i ; /* the first declaration */
    		{
    			int i ; /* the second declaration */
    			i = 1 ; /* refers to the second declaration */
    		}
    		i = 1 ; /* refers to the first declaration
    	}