Reputation: 22813
Why does this Compile:
int main()
{
{}
}
But this does not:
{}
int main()
{
}
Upvotes: 20
Views: 9173
Reputation: 279215
{}
is a do-nothing statement (specifically in the C grammar it is an empty compound-statement). You can put statements in functions. You can't put statements elsewhere.
I suppose the reason the standard doesn't forbid an empty statement in your first example is that although it's pointless, it does no harm, and introducing rules for when braces are allowed to be empty would complicate the grammar for no benefit.
And, to be pedantic, I suppose I should point out that neither does the grammar define any other construct at file scope, of which {}
is a valid instance, and that's why the second one is invalid.
Upvotes: 20
Reputation: 123458
Because the only things that may appear at the top level of a translation unit are declarations or function definitions; compound statements (empty or not) may not appear at that level.
Upvotes: 3
Reputation: 181270
Because code defined in a global scope is not allowed in C. Remember, in C, every line of code but variable declaration/initialization must lie within a function.
If you are inside a function you can have all {}
blocks you want.
Upvotes: 5
Reputation: 7132
First case, you're defining a block inside a function, which is allowed (it limits visibility). Second case, you're defining an anonymous block, which is not allowed (it needs to be predeceded by a function definition, otherwise, the compiler will never know when it will have to execute it)
Upvotes: 33