Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly Braces in C and C++

Tags:

c++

c

Why does this Compile:

int main() 
{
    {}  
}

But this does not:

    {}

int main() 
{  
}
like image 303
Sadique Avatar asked Apr 15 '11 16:04

Sadique


2 Answers

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)

like image 60
Bruce Avatar answered Sep 26 '22 18:09

Bruce


{} 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.

like image 45
Steve Jessop Avatar answered Sep 25 '22 18:09

Steve Jessop