wiesniak
wiesniak

Reputation: 583

Order of evaluation in sequence of bitwise OR

Consider following code:

#include <stdint.h>
#include <vector>
#include <iostream>
int main()
{
    typedef std::vector<uint8_t> rawbytes;
    rawbytes data({0xaa,0xbb,0xcc,0xdd});
    rawbytes::iterator data_it = data.begin();

    uint32_t as_int = (*data_it++ << 24 ) | ( *data_it++ << 16 ) | ( *data_it++ << 8 ) | *data_it++;     

    std::cout << std::hex << as_int << std::endl;
}

The output from this code is what I was expecting:

aabbccdd

Actually I wrote similar code and I realized that i'm not sure if it is guaranteed to work.

My doubts are placed in line:

uint32_t as_int = (*data_it++ << 24 ) | ( *data_it++ << 16 ) | ( *data_it++ << 8 ) | *data_it++;

If it is guaranteed that evaluation will be performed from left to right, so it means in this order? :

1: (*data_it++ << 24 )
2: (*data_it++ << 16 )
3: (*data_it++ << 8 )
4: *data_it++

My understanding is following: From "|" operator point of view, it doesn't matter which side of operator will be performed first. So it means that this code work as (primarily) expected, but actually by accident.

So my question is, if it is guaranteed, and why ?

Upvotes: 2

Views: 194

Answers (1)

Bathsheba
Bathsheba

Reputation: 234715

There are no such guarantees.

Unlike its cousin ||, | is not a sequencing point.

The behaviour of your program is undefined.

Upvotes: 6

Related Questions