-Wsequence-point warning - what does it mean and does it violate ANSI C standard?

℡╲_俬逩灬. 提交于 2020-02-22 06:11:21

问题


In line

tab[i] = tab[i+1] - tab[i] + (tab[i+1] = tab[i]);

I have a warning

[Warning] operation on '*(tab + ((sizetype)i + 1u) * 4u)' may be undefined [-Wsequence-point]

I want to swap these two integer arrays elements without temporary variable and without violation of ANSI C. Program still works, but is it ok?


回答1:


Your code relies on behaviour that is not covered by the standard. So your code may behave differently on different compilers, different versions of the same compiler and even behave differently depending on the surrounding code.

The problem is that you evaluate and assign to tab[i+1] without a separating sequence point. It may seem obvious to you that your program will perform the calculation from left to right, but the C standard does not require this. A compiler could compile your code as:

tab[i+1] = tab[i];
tab[i] = tab[i+1] - tab[i] + tab[i+1];

As a separate note. Swapping two variables is a highly optimised and easily recognisable operation, any optimising compiler will choose the fastest instructions if you write:

int temp = tab[i];
tab[i] = tab[i+1];
tab[i+1] = temp;


来源:https://stackoverflow.com/questions/40677318/wsequence-point-warning-what-does-it-mean-and-does-it-violate-ansi-c-standard

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