user14826940
user14826940

Reputation: 9

Encountered a weird warning : operation on 'C' may be undefined [-Wsequence-point]

#include <stdio.h>
int main(void)
{
    unsigned char A = 0xEB;
    unsigned char B = 0xE5;
    unsigned char C = 0x0; 
    printf("%#x\n",A^B);
    
    printf("%d %#x",C = A^B,C = A^B);//This line cause the warning

    //*[Warning] operation on 'C' may be undefined [-Wsequence-point]*
}

My compiler: TDM-GCC 9.2.0

What caused this warning?

Upvotes: 0

Views: 198

Answers (2)

John Bode
John Bode

Reputation: 123558

6.5 Expressions
...
2    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)
84) This paragraph renders undefined statement expressions such as
          i = ++i + 1;
          a[i++] = i;
while allowing
          i = i + 1;
          a[i] = i;
C 2011 Online Draft

In the statement

printf("%d %#x",C = A^B,C = A^B);

the expressions C = A^B have a side effect (assign a new value to C) and they are unsequenced relative to each other (function arguments are not guaranteed to be evaluated from left to right, right to left, or any other order, and their evaluations may even be interleaved), hence the warning. Even though C is being assigned the same value both times, the behavior is still undefined.

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

You're assigning the same variable twice, without having a sequence point in between, hence the warning. To avoid this, do

 C = A^B;  // determine the value of `C`
 printf("%d %#x",C ,C); // just use `C` as argument

To clarify, having it either

printf("%d %#x",C = A^B,C);

or

printf("%d %#x",C ,C = A^B);

won't work, as the order of evaluation of function argument is unspecified. You need to have the value calculated before and use the variable which stored the result as the argument to printf().

Upvotes: 0

Related Questions