In which order are the increment expressions on the right evaluated in the assignment statement? Is it undefined?

北城以北 提交于 2019-12-01 12:32:49

问题


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;
}

Output:

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

回答1:


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.

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.



来源:https://stackoverflow.com/questions/45262357/in-which-order-are-the-increment-expressions-on-the-right-evaluated-in-the-assig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!