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

Different behaviour of comma operator in C++ with return?(C ++中逗号运算符的不同行为与返回?)

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

问题描述

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

#include <iostream>
int main() {
    int x;
    x = 2, 3;
    std::cout << x << "
";
    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 << "
";
    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,32被求值然后其结果被丢弃,然后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.

关于 Expressions 和 声明

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 是这里的表达式.

x = 2,3; is expression statement, x = 2,3 is the expression here.

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

An expression followed by a semicolon is a statement.

语法:attr(可选) 表达式(可选) ;(1)

return 2,3;是跳转语句(return 声明),2,3 是这里的表达式.

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

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

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

本文标题为:C ++中逗号运算符的不同行为与返回?

基础教程推荐