We can define variables anywhere in the body of a function.
Variables exist only within the block in which they're defined.
The variable cease to exist at the next closing brace.
The variables declared at the beginning of an outer block exist in the inner block.
Variables created when they're declared and destroyed at the end of a block are called automatic variables.
The extent where a given variable is visible is called the variable's scope.
If you try to reference a variable outside its scope, you'll get a compile time error.
The following code shows variable scope:
{ int a = 0; // Create a // Reference to a is OK here // Reference to b is an error here - it hasn't been created yet { int b = 10; // Create b // Reference to a and b is OK here } // b dies here // Reference to b is an error here - it has been destroyed // Reference to a is OK here } // a dies here
#include <stdio.h> int main(void) { int count1 = 1; // Declared in outer block do/* w ww. j av a 2 s.co m*/ { int count2 = 0; // Declared in inner block ++count2; printf("count1 = %d count2 = %d\n", count1, count2); } while (++count1 <= 5); // count2 no longer exists printf("count1 = %d\n", count1); return 0; }