赋值语句中右边的增量表达式是按什么顺序计算的?它是未定义的吗? [英] In which order are the increment expressions on the right evaluated in the assignment statement? Is it undefined?

查看:18
本文介绍了赋值语句中右边的增量表达式是按什么顺序计算的?它是未定义的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近了解了 C 中的未定义行为,但此特定代码在站点中用作逗号作为运算符"的示例,虽然我了解第 2 行中 y = x++ 的方式,但我不明白按什么顺序计算第 2 行中的子表达式.我认为这是未定义的行为,但我不确定,因为该网站没有提及任何此类内容.

I recently learnt about undefined behaviour in C, but this particular code was used in a site as an example for 'comma as an operator', and while I understand how y = x++ in line 2, I dont understand in what order the sub expressions in line 2 are evaluated. I think it is undefined behaviour, but I'm not sure,because the site didn't mention anything as such.

int main()
{
    int x = 10, y;

    y = (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++);

    printf("y = %d\n", y);
    printf("x = %d\n", x);

    return 0;
}

输出:

x = 11
x = 12
y = 12
x = 13

推荐答案

这不是未定义的行为.
您首先将 x 增加到 11,打印它,然后将它增加到 12 并打印它,然后在评估后增加它,所以 x 将是 13,整个表达式将评估为 12.

It is not undefined behaviour.
You first increase x to 11, the print it, then increase it to 12 and print it, then increase it after evaluation, so x will be 13 and the whole expression will evaluate to 12.

这是由于 C 中的逗号运算符是一个序列点造成的,这意味着可以保证之前评估的所有副作用都已经执行,并且后续评估的副作用尚未执行.

This is caused due to the comma operator in C being a sequence point, which means it is guaranteed all side effects of previous evaluations will have been performed, and no side effect from subsequent evaluations have yet been performed.

这篇关于赋值语句中右边的增量表达式是按什么顺序计算的?它是未定义的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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