The value of single curly braces in C

I came across a bit of code that contains a pair of code blocks denoted by curly braces {} . There is no line before code blocks mark them as part of if , function definitions, or anything else. Just a block of code floating in the middle of a function. Does that make sense? gcc seems completely happy going through the code; I can only imagine that this is a way to allow the original encoder to visually separate the blocks of functionality ...

+6
c syntax formatting
source share
5 answers

It creates a scope. Are there automatic variables inside blocks? If so, then the scope of these variables is limited to a block. This is useful for temporary variables that you don’t want to pollute the rest of the function, and also useful when writing C89, where the variable definitions should be at the beginning of the block.

So, instead of:

 int main() { int a = 0; int b; int i; for (i = 1; i < 10; ++i) { a += i; } b = a * a; // do something with a and b } 

You may have:

 int main() { int a = 0; { int i; for (i = 1; i < 10; ++i) { a += i; } } { int b = a * a; // do something with a and b } } 

Obviously, if you do this, you also need to ask yourself if the blocks would be better used as separate functions.

+11
source share

For viewing, autonomous curly brackets are used - any variables declared in the block are not visible outside it.

+9
source share

If the code blocks contain declarations of local variables (your description is not clear what is inside), they may be there to limit the scope of these variables. I.e.

 int i = ...; // i is visible here { int j = ...; // both i and j are visible here } // j went out of scope, only i is visible here 
+2
source share

Used to create an area. An area useful for declaring variables that can only be used in this area. For example, if a variable is declared before curly braces, it can be used inside curly braces after them. In contrast, if a variable is declared inside curly braces, it can only be used inside curly braces. Hope this helps.

+2
source share

Usually this means that it was written to declare a variable part of the path through a large function, but the variable is needed only in a very limited area or may even hide something. It is completely legitimate - it just enters a block. The big problem is always "what is the correct indentation for this code."

It can also be used by preprocessors that convert some other language into generated C. The converted material is often wrapped in a block (and possibly #line directives).

0
source share

All Articles