问题
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