unsequenced modification and access to pointer

Deadly 提交于 2019-12-23 08:29:31

问题


I'm getting a warning for this C expression:

*p0++ = mult(*p0, psign[i1]); 

The warning is:

unsequenced modification and access to 'p0' [-Wunsequenced]

I think the expression should be modified to this:

*p0 = mult(*p0, psign[i1]);
p0++;

Is the behavior (after modification) going to be as intended? I would think that the pointer increment should happen after the value pointed to by p0 has been updated.


回答1:


The snippet you have provided above invokes undefined behavior. According to C standard

C11: 6.5 Expressions:

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.84).

In the expression *p0++ = mult(*p0, psign[i1]), the modification to p0 on left side of the assignment operator is not sequenced before or after the use of p0 on right hand side of the expression. Therefore, the snippet

*p0++ = mult(*p0, psign[i1]);   

is not equivalent to

*p0 = mult(*p0, psign[i1]);
p0++;                       // Side effect to p0 is guaranteed after the use  
                            // of p0 in mult function


来源:https://stackoverflow.com/questions/32017561/unsequenced-modification-and-access-to-pointer

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