Why does this Compile:
int main()
{
{}
}
But this does not:
{}
int main()
{
}
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)
{}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With