next up previous contents index
Next: Pass by value and Up: Introduction Previous: Introduction   Contents   Index


Local variables

You can declare variables at the start of the function body:

  
/*  return the harmonic mean of three numbers */
float my_mean(float a, float b, float c) {

  float t;

  t = 1.0/a;
  t = t + 1.0/b;
  t = t + 1.0/c;

  return 3.0/t;
}
The variable t declared here is only visible in the body of the function; any other variable called t declared elsewhere will not be effected by calls to my_mean:

  
float t;   /*  this is visible everywhere (a `global' variable)  */

float my_mean(float a, float b, float c) {
  float t;
  /*  in the body of the function, references to t effect
      the local variable t, declared on the line above  */
  /* .. */
}

int main(void) {
  float p;
  t = 1;
  p = my_mean(3.0, 4.0, 5.0);
  /*  t still equals one  */  
}
Each time the function is called, memory for the local variable t will be allocated afresh, so its value will not be preserved between calls. If you do want the value to be preserved, use static.



CATAM admin 2010-02-23