C Syntax – Idiomatic Use of Arbitrary Blocks in C

csyntax

A block is a list of statements to be executed. Examples of where blocks come up in C are after a while statement and in if statements

while( boolean expression)
    statement OR block

if (boolean expression)
    statement OR block

C also allows a block to be nested in a block. I can use this to reuse variable names, suppose I really like 'x'

int x = 0;
while (x < 10)
{
    {
        int x = 5;
        printf("%d",x)
    }
    x = x+1;
}

will print the number 5 ten times. I guess I could see situations where keeping the number of variable names low is desirable. Perhaps in macro expansion. However, I cannot see any hard reason to need this feature. Can anyone help me understand uses of this feature by supplying some idioms where it is used.

Best Answer

The idea isn't to keep the number of variable names low or otherwise encourage reuse of names, but rather to limit the scope of variables. If you have:

int x = 0;
//...
{
    int y = 3;
    //...
}
//...

then the scope of y is limited to the block, which means that you can forget about it either before or after the block. You see this used most often in connection with loops and conditionals. You also see it more often in C-like languages such as C++, where a variable going out of scope causes it's destruction.

Related Topic