Beginning C by Ivor Horton

Beginning C by Ivor Horton

Author:Ivor Horton
Language: eng
Format: epub, pdf
ISBN: 9781430248811
Publisher: Apress


int main(void)

{

int count1 = 1; // Declared in outer block

do

{

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;

}

You will get the following output from this program:

count1 = 1 count2 = 1

count1 = 2 count2 = 1

count1 = 3 count2 = 1

count1 = 4 count2 = 1

count1 = 5 count2 = 1

count1 = 6

How It Works

The block that encloses the body of main() contains an inner block that is the do-while loop. You declare and define count2 inside the loop block:

do

{

int count2 = 0; // Declared in inner block

++count2;

printf("count1 = %d count2 = %d\n", count1, count2);

} while( ++count1 <= 5);

So count2 is re-created on every loop iteration with the initial value 0 and its value is never more than 1. During each loop iteration, count2 is created, initialized, incremented, and destroyed. It only exists from the statement that declares it down to the closing brace for the loop. The variable count1, on the other hand, exists at the main() block level. It continues to exist while it is incremented, so the last printf() produces the value 6.

If you modify the program to make the last printf() output the value of count2, it won’t compile. The error is caused because count2 no longer exists at the point where the last printf() is executed.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.