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

int main(void) {
    printf("hello\n"), return 0;
}
  • 代码如上,,不能和return、break、continue连用,编译器会报错“expected expression”,这是语法上的限制吗?如果是,为什么要有这种限制呢?

阅读 4.8k
2 个回答

好问题!我特意查了下 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的值.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进