开发者

When is a semicolon after } mandated in c/c++?

if(...) {
  ...
}

It seems in the above case a ; is op开发者_JS百科tional,when is a semicolon after } necessary in c/c++?


int a[2] = {1,2}, j = 5;

When initialization of array or structure are done with {} all the subsequent variables are declared after ,.

Edit: As you changed your question; ; is mandatory after the class, enum, initialization syntax declarations.

class A {};  // same for `struct
enum E {};   // enum class (c++0x)
int a[] = {1,2};  // array or object initialization

And as per comment by @rubenvb:

do {} while(condition);


A semicolon by itself is an empty statement, and you can add extra ones anywhere a statement is legal. Therfore it would be legal to put a semicolon right after the braces following your if, although it wouldn't be related to the if at all. The only place I can think of where a semicolon is required right after a bracket is after a class declaration in C++.


A semicolon after a close brace is manadatory if this is the end of a declaration. If it is the end of a block statement then no semicolon is needed, and if one is used, it makes an additional empty statement, which may be illegal if this is the middle of a if-else or a do-while (or a try-catch in C++)


Semicolons are required many places not after a close brace (at the end of any statement except a block-statement, at the end of any declaration, even if there is no }, in a for clause, etc, but generally braces are not involved in any of those.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜