Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of operations in C. ++ vs |=, which occurs first?

I have the following code that I'm reading through:

if( (i%2) == 0 ){ 
    *d = ((b & 0x0F) << 4); 
}
else{
    *d++ |= (b & 0x0F); 
};

I'm looking specifically at the else statement and wondering in what order this occurs? I don't have a regular C compiler, so I can't test this. When we are performing *d++ |= (b & 0x0F);, what order does this occur in?

like image 668
chris Avatar asked May 19 '10 13:05

chris


2 Answers

The ++ is applied on the pointer d, not on the lvalue that is being assigned to, *d.

If you really want to, you can think of it like this:

  1. The value of b is bitwise-AND:ed with the constant 0x0f
  2. The resulting bit pattern is bitwise-OR:ed into the value that d points at.
  3. The pointer d is incremented to point at the next value.
like image 101
unwind Avatar answered Sep 24 '22 03:09

unwind


d++ returns the value d had before it was incremented. This is then dereferenced by the *, and that location is what the |= is performed on. So the data at the location prior to incrementing d will have (b & 0x0F) ored into it.

In general, if the order of operations in a line of code is not clear at a glance, refactor the line into its constituent operations until it is. Generated code does not become any faster or more compact simply from squeezing lots of operations onto one line of C! There is no good reason to sacrifice comprehensibility in this way. Replace the line with

*d |= (b & 0x0F); 
d++;
like image 32
moonshadow Avatar answered Sep 25 '22 03:09

moonshadow