Different behaviour of comma operator in C++ with return?(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,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.
关于 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 ++中逗号运算符的不同行为与返回?
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
