Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the += operator in C be used to demonstrate that the same array index is used for an array reference?

I was looking through Expert C Programming by Peter Van Der Linden recently and came across this use for the += operator:

"If you have a complicated array reference and you want to demonstrate that the same index is used for both references, then:

node[i >> 3] += ~(0x01 << (i & 0x7)); 

is the way to go."

As much as I've tried, I can't figure out this code. I'm hoping someone here can explain what is actually going on and why it can be used to demonstrate that the same index is used?

like image 812
arun Avatar asked Jan 31 '12 18:01

arun


2 Answers

My interpretation of the quote is that

node[COMPLICATED_EXPRESSION] += STUFF;

is preferable to

node[COMPLICATED_EXPRESSION] = node[COMPLICATED_EXPRESSION] + STUFF;

since it's easier to see at a glance what the intent is.

More so if STUFF is also complicated, since this makes the overall expression even harder to parse at a glance.

In the book, van der Linden explains where the code he shows came from:

We took this example statement directly out of some code in an operating system. Only the data names have been changed to protect the guilty.

like image 108
NPE Avatar answered Sep 18 '22 05:09

NPE


I haven't read the book in question, so I can only go off of your quote. I suspect that what he is referring to is this:

Instead of writing:

array[complicated_expression] = array[complicated_expression] + something_else

(note the two references to the same index of the array)

you can write:

array[complicated_expression] += something_else

This makes it clear that the complicated expression is the same in "both references".

An alternative way to do this would be to use a temporary variable:

int index = complicated_expression;
array[index] = array[index] + something_else

But that isn't as concise. (It is more general though, as you can use it for cases where you're doing some operation that doesn't have an X= operator.)

like image 21
Laurence Gonsalves Avatar answered Sep 21 '22 05:09

Laurence Gonsalves