Why ternary operation may be undefined

Viewed 122

Working with GNU/GCC

With this code :

static uint8_t write_idx=0;
write_idx = write_idx==127 ? 0 : ++write_idx;

I get this warning :

warning: operation on 'write_idx' may be undefined [-Wsequence-point]

Do you know what generates this warning ?

EDIT :

write_idx = write_idx==127 ? 0 : write_idx+1;

Same behaviour but no warning thanks @pmg

1 Answers

This can be reduced to:

write_idx = ++write_idx;

The compiler warns because there are two places writing into write_idx without a sequence point. This means the standard does not define what should happen.

Perhaps you don't know that the ++ pre-increment operator modifies the variable and you wanted to write this instead:

write_idx = write_idx==127 ? 0 : write_idx + 1;
Related