C ++中逗号运算符与return的不同行为? [英] Different behaviour of comma operator in C++ with return?

查看:228
本文介绍了C ++中逗号运算符与return的不同行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此(请注意逗号运算符):

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

输出 2 .

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

However, if you use return with the comma operator, this:

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

输出 3 .

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

Why is the comma operator behaving differently with return?

推荐答案

根据操作员优先级逗号运算符的优先级低于operator=,因此x = 2,3;等效于(x = 2),3;. (运算符的优先级决定了运算符如何根据其优先级而比其他运算符更严格或更松散地绑定到其参数.)

According to the Operator Precedence, comma operator has lower precedence than operator=, so x = 2,3; is equivalent to (x = 2),3;. (Operator precedence determines how operator will be bound to its arguments, tighter or looser than other operators according to their precedences.)

请注意,此处的逗号表达式为(x = 2),3,而不是2,3.首先评估x = 2(并完成其副作用),然后丢弃结果,然后评估3(实际上不执行任何操作).这就是x的值为2的原因.请注意,3是整个逗号表达式(即x = 2,3)的结果,它将不会用于分配给x. (将其更改为x = (2,3);,将为x分配3.)

Note the comma expression is (x = 2),3 here, not 2,3. x = 2 is evaluated at first (and its side effects are completed), then the result is discarded, then 3 is evaluated (it does nothing in fact). That's why the value of x is 2. Note that 3 is the result of the whole comma expression (i.e. x = 2,3), it won't be used to assign to x. (Change it to x = (2,3);, x will be assigned with 3.)

对于return 2,3;,逗号表达式为2,3,对2求值,然后将其结果丢弃,然后对3求值并作为整个逗号表达式的结果返回,并由稍后返回声明.

For return 2,3;, the comma expression is 2,3, 2 is evaluated then its result is discarded, and then 3 is evaluated and returned as the result of the whole comma expression, which is returned by the return statement later.

有关表达式

Additional informations about Expressions and Statements

表达式是运算符及其操作数的序列,用于指定计算.

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

x = 2,3;表达式语句x = 2,3是在这里表达.

后跟分号的表达式是语句.

An expression followed by a semicolon is a statement.

语法:attr(optional) expression(optional) ; (1)

return 2,3;跳转语句(

return 2,3; is jump statement (return statement), 2,3 is the expression here.

语法:attr(optional) return expression(optional) ; (1)

这篇关于C ++中逗号运算符与return的不同行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆