carl.hiass
carl.hiass

Reputation: 1774

Usage of enclosing scope in C

Are inner-scopes ever used in C, or is this similar to something like a goto statement that isn't used too much in production code? The only thing I can think of that might use it is making something volatile temporarily, for example:

int main(void) 
{ 
    int a=1; 
    const int b=4; 
    printf("a=%d, b=%d\n", a, b); 
    { 
        int b=5; 
        printf("a=%d, b=%d\n", a, b); 
    } 
}

But that seems like a pretty non-practical example. How would these be used in practice?

Upvotes: 1

Views: 271

Answers (3)

Emon46
Emon46

Reputation: 1626

we don't use them very often in production code. but this one very useful when you need your variable's scope very specific. as far our use case, suppose you are coding in production code, and you want your some of variable's scope very specific . in this circumstances, we just use block {.....} to limit variable scope.

Upvotes: 1

dxiv
dxiv

Reputation: 17648

One case when blocks are required is defining local variables in a switch statement.

switch(foo())
{
case 0:
    printf("no '{}' block generally required, except...\n");
    break;

case 1:
  {
    int n = bar();
    printf("%d\n", (n + 1) * n);
  }
    break;

//...
}

Without the {} block, the code would not compile because case 1: expects a statement right after, and declarations are not statements in C.

(Incidentally, the block is usually required in C++, too, though for an entirely different reason, because initialization of n would be skipped by other case labels.)

Upvotes: 3

Caleb
Caleb

Reputation: 125007

Are inner-scopes ever used in C, or is this similar to something like a goto statement that isn't used too much in production code?

Not so much by themselves, but inner scopes come up naturally all the time as the bodies of control statements such as loops and conditional statements. For example, a variable declared inside the body of a loop goes out of scope at the end of each iteration of the loop and is instantiated again during the next iteration.

Upvotes: 3

Related Questions