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?
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With