为什么卷曲的括号后不需要分号?

2022-09-04 08:23:40

我知道在语句之后需要分号(我说的是Java,C++和类似语言),但在卷曲的括号之后不需要分号。为什么会这样?

if (a > b) 
  printf("hello!"); // semicolon is mandatory

if (a > b) {
  printf("hello!");
} // semicolon is not required

原因何在?我的意思是,这背后的理论是什么?


答案 1

因为大括号用于对语句进行分组,但它们本身不是语句。


答案 2

因为语言被定义为:

statement:
    labeled-statement
    expression-statement
    compound-statement
    selection-statement
    iteration-statement
    jump-statement
    declaration-statement
    try-block

labeled-statement:
    identifier : statement
    case constant-expression : statement
    default : statement

expression-statement:
    expressionopt ; 

compound-statement:
    { statement-seqopt } 

statement-seq:
    statement
    statement-seq statement

selection-statement:
    if ( condition ) statement
    if ( condition ) statement else statement
    switch ( condition ) statement

condition:
    expression
    type-specifier-seq declarator = assignment-expression

iteration-statement:
    while ( condition ) statement
    do statement while ( expression ) ; 
    for ( for-init-statement conditionopt ; expressionopt ) statement

for-init-statement:
    expression-statement
    simple-declaration

jump-statement:
    break ;
    continue ;
    return expressionopt ; 
    goto identifier ; 

declaration-statement:
    block-declaration 

所有常规控制语句都是彼此递归构建的。真正的工作是由 .如果您注意到 始终由 终止。其他要注意的语句是 .expression-statementexpression-statement;jump-statement

但主要原因是{}块之后不需要它们来允许解析语句。easy