Is this an undefined behavior in C? [duplicate]

♀尐吖头ヾ 提交于 2019-12-01 13:26:29

问题


I am running my C code on gcc to understand pre/post increment operator. However the results that I see are not what I expected. Like for the line 6, since i is 5, it should have been

8 7 6 5 5

But it is 8 7 6 5 8

Then coming to the last line, it displays 14 14 14 14. Can someone please explain this behavior. I had expected 14 14 13 12

Is this compiler dependent? Is the beahviour of printf function on sequence points undefined?

#include <stdio.h>

int main()
{
        i = 5;
        printf("%d %d %d %d %d \n", i, i++, i++, i++, i);
        printf("%d \n", ++i);
        printf("%d \n", ++i);
        printf("%d \n", ++i);
        printf("%d %d %d %d \n", i, ++i, ++i, ++i);

}

回答1:


The Standard states that

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.

And these are the places where you will find sequence points:

  • at the end of the evaluation of a full expression (a full expression is an expression statement, or any other expression which is not a subexpression within any larger expression);

  • at the ||, &&, ?: and comma operators; and

  • at a function call (after the evaluation of all the arguments, and just before the actual call).

An elaboration of the last point: the comma operators in a function call are not sequence points and the expressions between the ,s can be evaluated in any arbitrary order.

Check this and this for better understanding.

In printf("%d %d %d %d %d \n", i, i++, i++, i++, i);, you are writing to the same memory location more than once between two sequence points, thus invoking undefined behaviour.



来源:https://stackoverflow.com/questions/47385214/is-this-an-undefined-behavior-in-c

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