Reputation: 55739
I know that in C# and JavaScript, the following is perfectly valid:
{
var foo;
}
Is having a bare block valid in C too?
i.e. is this valid C?
{
int foo;
}
Upvotes: 2
Views: 155
Reputation: 59691
Yes it's totally fine!
As an example:
#include <stdio.h>
int main() {
{
int i = 5; //If you declare i outside you can use both print statements
printf("%d", i);
}
//printf("%d", i); Note that i is out of scope here
return 0;
}
Upvotes: 5
Reputation: 145839
Is this valid in C too?
Yes, it is and it is called a compound statement.
From the C11 Standard:
6.8.2 Compound statement
Syntax
1 compound-statement:
{ block-item-listopt }
block-item-list:
block-item
block-item-list block-item
block-item:
declaration
statement
A compound-statement is itself a statement in C.
For example this block is a valid block:
{
{
{
printf("Hello world");
}
}
}
Even this one is valid:
{{{}}}
{}
is an empty compound statement.
Upvotes: 7