Home > Software engineering >  Why is the `operation on 'i' may be undefined`and how to fix this warning?
Why is the `operation on 'i' may be undefined`and how to fix this warning?

Time:09-30

The operation on 'i' may be undefined appears at the second i in the line as follows:

int i = 4;
const uint16_t rawVoltage = (rxBuffer[i  ]<<8) | rxBuffer[i  ]; 

I believe it is related to the order of operations, but I guess the parenthesis has priority over the last increment.

Btw, the code works fine, as expected, just want to address the warning.

CodePudding user response:

Parentheses affect parsing but not order of evaluation. You have two operations in your expression that modify i: i on the left-hand side and i on the right-hand side.

In general the order of evaluation is not specified in C . For some operators certain sequencing rules apply, but in particular | does not enforce any sequencing of the two operands. Therefore there is no sequencing rule enforcing any order between the left- and right-hand i .

The standard says that if the value computation or a side effect is unsequenced with another side effect on the same scalar object, then the behavior is undefined. That is the case here on i.

The solution is to split the statement into two:

uint16_t rawVoltage = (rxBuffer[i  ]<<8);
rawVoltage |= rxBuffer[i  ];

Btw, the code works fine, as expected, just want to address the warning.

That's by pure luck. The program has undefined behavior and compilers do make use of that for optimization. Even if it was not undefined behavior the order between the two operands would be unspecified and compilers will also reorder evaluation in such cases if that gives an optimization advantage or they may by default use different orders.

  •  Tags:  
  • c
  • Related