Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 576
residue Avatar asked Feb 05 '23 16:02

residue


1 Answers

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;
like image 159
Mats Avatar answered Apr 06 '23 09:04

Mats