编译器如何根据优先级和关联性解释此表达式
How does the compiler interpret this expression, in terms of Precedence and Associativity?
这是C++入门5th的练习:
Exercise 4.33: Explain what the following expression does(Page158): someValue ? ++x, ++y : --x, --y
代码:
bool someVlaue = 1;
int x = 0;
int y = 0;
someVlaue ? ++x, ++y : --x,--y;
std::cout << x << std::endl << y << std::endl;
我尝试了Gcc4.81
和Clang3.5
,都给了我:
1
0
Press <RETURN> to close this window...
为什么不1
和1
?谁能解释一下它是如何解释的?
由于逗号运算符的优先级非常低,因此表达式
someValue ? ++x, ++y : --x,--y;
相当于:
(someValue ? ++x, ++y : --x),--y;
因此,执行++x, ++y
表达式(将x
和y
设置为 1),然后在末尾执行表达式--y
,将y
恢复为 0。
注意 - 逗号运算符引入了序列点,因此多次修改y
不会产生未定义的行为。
表达式
someValue ? ++x, ++y : --x, --y
被评估为
(someValue ? ((++x), (++y)) : (--x)), (--y)
如您所见,y
被修改了两次,一次递增,一次递减,因此结果是1 0
而不是1 1
。
相关文章:
- 请解释"函数1(p1,p2,p3);"的输出
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 被解释为低级别const的const对象的地址
- 计算每个节点的树高,帮助我解释这个代码解决方案
- MSVC将仅移动结构参数解释为指针
- 内联程序集printf将整数解释为地址
- 有人能解释一下为什么下界是这样工作的吗C++的
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 我是c ++的新手,你能解释一下在这种情况下的指针吗
- 有人能为我解释一下C++代码吗
- 你能解释一下什么运行时错误是如何解决它的吗?
- 请解释字谜的代码,我看不懂计数器数组,每个值已经是0
- C++ 优先性和关联性
- 有人可以向我解释为什么控制台输出 0 吗?
- 有人可以解释一下这段代码如何能够反转字符串
- 在 C++ 中解释多维向量的语句时感到困惑
- 解释一下 for (char c : str) 的作用?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- 隐式重新解释引用时强制转换,没有警告/错误
- 编译器如何根据优先级和关联性解释此表达式