开发者社区> 问答> 正文

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

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

•代码如上,,不能和return、break、continue连用,编译器会报错“expected expression”,这是语法上的限制吗?如果是,为什么要有这种限制呢?

展开
收起
杨冬芳 2016-05-30 19:43:48 2977 0
1 条回答
写回答
取消 提交回答
  • IT从业

    好问题!我特意查了下 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 都属于语句,因此不行。

    2019-07-17 19:21:01
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载