Peter Peter - 28 days ago 5
C++ Question

Compiler warning about undefined operation

Here is my code to deserialize uint64_t value from a byte array:

uint8_t* s = blah;

uint64_t output =
(((uint64_t)*s++) << 56) +
(((uint64_t)*s++) << 48) +
(((uint64_t)*s++) << 40) +
(((uint64_t)*s++) << 32) +
(((uint64_t)*s++) << 24) +
(((uint64_t)*s++) << 16) +
(((uint64_t)*s++) << 8) +
(((uint64_t)*s) );


I am compiling this code with g++ version 5.4 on Ubuntu.

While the code works exactly as expected, I get a compile time warning on the last line:

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


Wondering what could potentially be wrong and how I can fix it. Regards.

Answer

Your code has unsequenced modifications of the variable s. This behaviour is undefined. You can fix it by using indexes instead of advancing the pointer (I'm assuming you're reading a little-endian variable. This is non-obvious from your code):

uint64_t output =
     (((uint64_t)s[0]) << 56) +
     (((uint64_t)s[1]) << 48) +
     (((uint64_t)s[2]) << 40) +
     (((uint64_t)s[3]) << 32) +
     (((uint64_t)s[4]) << 24) +
     (((uint64_t)s[5]) << 16) +
     (((uint64_t)s[6]) <<  8) +
     (((uint64_t)s[7])        );