next up previous contents index
Next: Automatic conversions and casts Up: Variables Previous: Variables   Contents   Index


Declarations and scope

The syntax of most variable declarations is simple: the type of the variable, followed a list of names, or names with array bounds:

  
int x;
int y[2], b, c[3];
double a[3][3][3];
char names[][80];
struct point x;
enum colour foreground;
int *buf, *k;  /* pointers have a special syntax,
                  buf and k are both int* (pointers-to-ints)  */
The name can contain any sequence of numbers, letters, or the underscore character _ but cannot start with a number. The ANSI C standard dictates that only the first six characters in a variable's name are significant, but this restriction is ignored by most C compilers. A variable can only be declared at the start of a compound-statement,

  
{ /*  curly brackets starting a compound-statement  */
  int   n_iters;
  float answer;

  /*  use n_iters and answer here  */

} /*  end of the compound-statement  */
and can be used anywhere inside the compound-statement (we say that the `scope' of the variable is confined to the compound-statement), or outside of any compound-statement, when it can be accessed from any point below its declaration. In the latter case, the variables are frequently declared right at the top of the program, and are thus visible everywhere (so called `global' variables):

  
int i;

int f(void) {
  /*  can use i here  */
}

int main(void) {
  /*  can use i here too  */
}
Variables can be initialized when they are declared:

  
int f(int k) {
  int n_0 = 23;  /*  fine  */
  int m_0 = k;  
}
If you start a new compound-statement, for example with an if-else construction, you can use the opportunity to declare new variables, but the new variables will only be visible inside the new compound-statement, below the declaration.

  
int f(int k) {
  int n = 1;

  if (n == 1) { /*  we start a new compound-statement;
                    can now define more variables  */
    int m = 4;
    /*  can use n and m here  */
  } /*  end of the compound-statement  */
  /*  can't use m here, we're outside the 
      compound-statement it's declared in */
}
If a variable is declared when there is already a variable in scope with the same name, the second declaration obscures the first:

  
{
  int n = 1;
  /* .. */
  {
    int p = n;  /*  ok, the only n in scope is declared above */
    int n;      /*  declare a new n, shadowing the one above  */
    n = 23;     /*  effects the n declared on the line above  */
  }
 /*  n is 1 here, and there is no p in scope  */
}


next up previous contents index
Next: Automatic conversions and casts Up: Variables Previous: Variables   Contents   Index
CATAM admin 2010-02-23