Search code examples
cbit-shiftoperator-precedenceaddition

Why does adding values directly to a variable in C all at once and one at a time creates different values?


Why does the code

    int returnValue = val[0] << 24;
    returnValue += val[1] << 16;
    returnValue += val[2] << 8;
    returnValue += val[3];

produces a different result than int returnValue = val[0] << 24 + val[1] << 16 + val[2] << 8 + val[3];

When I provide the string 1.1.1.2, the separated addition equals 0x01010102 but the oneliner results in 0x00000000.

Why is that happening?


Solution

  • The reason this is occurring is because order of operations is incorrect for the oneliner.

    Example:

    int val[] = {1,2,3}
    //What the code is actually doing val[0] << (4 + val[1]) << (2 + val[1]) 
    //Or 1 << (6) << (5) and equivalent to  1 << 196 or 0 in a 32 bit integer.
    int inCorrect = val[0] << 4 + val[1] << 2 + val[2]; //This will fail
    
    //What I want the code to do
    // (1 << 4) + (2 << 2) + 3 = 16 + 8 + 3 = 27 or 0b011011 or 0x01B
    int correct = (val[0] << 4) + (val[1] << 2) + val[2]; //This will succeed