开发者

Curly Braces in C and C++

Why does this Compile:

int main() 
{
    {}  
开发者_Go百科}

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜