首页 > 为什么逗号运算符不能与return语句连用?

为什么逗号运算符不能与return语句连用?

int main(void) {
    printf("hello\n"), return 0;
}

好问题!我特意查了下 C Language References,找到了答案

原因在于: 逗号(comma)作为操作符(operator)只能连接表达式(expression),而 return 等不是表达式,而是语句(statement)。

先看官方定义:

comma operators: http://en.cppreference.com/w/c/language/operator_other

statements via http://en.cppreference.com/w/c/language/statements :

Statements are fragments of the C program that are executed in sequence. The body of any function is a compound statement, which, in turn is a sequence of statements and declarations

expressions via http://en.cppreference.com/w/c/language/expressions :

An expression is a sequence of operators and their operands, that specifies a computation.

表达式仅是一系列操作符及其操作数的有序组合,而语句则是一系列有固定结构的c片断,通常无返回值。

break, continue, return 都属于语句,因此不行。


是语法限制, "return 0" 不是一个expression. ref.

我的猜测是..让return是一个expression并无意义, 因为return执行完就跳走了, 没有东西可以使用这个expression的值.

【热门文章】
【热门文章】