c++ - C++中逗号运算符的不同行为与返回?

标签 c++ return language-lawyer operator-precedence comma-operator

这个(注意逗号操作符):

#include <iostream>
int main() {
    int x;
    x = 2, 3;
    std::cout << x << "\n";
    return 0;
}

输出 2

但是,如果您将 return 与逗号运算符一起使用,则:

#include <iostream>
int f() { return 2, 3; }
int main() {
    int x;
    x = f();
    std::cout << x << "\n";
    return 0;
}

输出 3

为什么逗号运算符与 return 的行为不同?

最佳答案

根据Operator Precedence , comma operator优先级低于 operator=,因此 x = 2,3; 等价于 (x = 2),3;。 (运算符优先级决定了运算符如何绑定(bind)到它的参数,根据它们的优先级比其他运算符更紧或更松。)

注意这里的逗号表达式是(x = 2),3,而不是2,3x = 2 首先被评估(并且它的副作用已经完成),然后结果被丢弃,然后 3 被评估(它实际上什么都不做)。这就是 x 的值是 2 的原因。注意 3 是整个逗号表达式的结果(即 x = 2,3),它不会用于分配给 x。 (改成x = (2,3);x会被赋值为3。)

对于return 2,3;,逗号表达式为2,32被求值然后其结果被丢弃,然后3 被评估并作为整个逗号表达式的结果返回,由 return statement 返回稍后。


关于 Expressions 的更多信息和 Statements

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

x = 2,3;expression statement , x = 2,3 是这里的表达式。

An expression followed by a semicolon is a statement.

Syntax: attr(optional) expression(optional) ; (1)

返回 2,3;jump statement ( return statement ), 2,3 是这里的表达式。

Syntax: attr(optional) return expression(optional) ; (1)

关于c++ - C++中逗号运算符的不同行为与返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39364263/

相关文章:

c++ - ADL with std::function:可以通过 std::function 的参数列表中的类型找到采用 std::function 对象的函数吗?

c++ - 嵌套两次的 sizeof 可以是依赖表达式吗?

c++ - 两个日期之间的秒数,包括闰秒

c - 输入无效用户时 getpwnam() 使程序崩溃

c - 在 glibc memmove 中强制转换为 signed int 的目的是什么?

c - 为什么 main 在这里不返回 0?

php - PayPal 自动返回不会发回任何 POST 数据

c++ - 在 msvs2010 上使用 curl 编译项目

c++ - 将 multimap 转换为 void 指针,然后返回 multimap

c++ - 在具有不同类型的 vector 中使用模板结构