Understanding the block scope of variables
We have already seen several instances of block scope. Function bodies consist of a block beginning with {
and ending with }
. Complex statements such as conditional statements and looping statements also consist of one or more blocks beginning with {
and ending with }
. Finally, it is possible to create an unnamed block anywhere with any other block that begins with {
and ends with }
. C is very consistent in its treatment of blocks, regardless of where they appear.
Variables declared within a block are created, accessed, and modified within that block. When that block completes, they are deallocated and are no longer accessible; the space they occupied is gone, to be reused by something else in the program.
When you declare and initialize variables within a function, those variables are visible to all statements within that function until the function returns or the final }
is...