Reputation:
Is creating local scopes with just a pair of brackets, would that be considered standard C?
#include <stdio.h>
int main(int argc, char *argv[]) {
{
register char x = 'a';
putchar(x); // works
}
//putchar(x); wont work
}
Or is it best to not use this? Is it a GCC compiler extension?
I have once been told that the accepted practice is a do {...} while (0);
loop. Is it true that all C compilers will recognise this practice just like it is safe to assume any given C compiler will recognise an if
statement?
I tried googling this, and my results were about scope behavior, and had nothing to do with manually applying scopes.
Upvotes: 1
Views: 207
Reputation: 223897
This is standard C.
Section 6.8p1 of the C standard gives the following syntax for a statement:
statement: labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement
Where a compound-statement
is defined in section 6.8.2p1:
compound-statement: { block-item-list(opt) } block-item-list: block-item block-item-list block-item block-item: declaration statement
What this says is that anyplace that a statement can occur, a compound statement (i.e. a set of statements surrounded by {}
) can occur.
Upvotes: 2
Reputation: 4554
Yes, it is standard; this is creation of block scope, as supported by C language.
Regarding "best to use" part, it depends, certainly it might be a bit confusing to some people.
This might come in very useful with generated code though, so you don't need to bother (as much) with unique identifiers for local vars:
int main(int argc, char *argv[]) {
{
int x = 4;
printf("%d\n", x);
}
{
int x = 5;
printf("%d\n", x);
}
}
Upvotes: 5
Reputation: 44250
Yes, it is standard; you can always introduce a new scope with an extra pair of {}
I often use it in conditionally compiled code, to avoid unused variable warnings:
#if DEBUG
{
struct node *tmp;
for (tmp=this; tmp; tmp= tmp->next) {
printf(stderr, "Node %u: %s\n", tmp->num, tmp->name);
}
}
#endif
Upvotes: 2