venta: (Default)
[personal profile] venta
Note to self:

3 + 8 << 2

is not the same as

3 + (8 << 2)

That's an hour you just spent tracking down a bug based on a mistake you've made several times before.

Yes, I know, brackets. Normally I'm assiduous about brackets. But for short lines like, say,

3 + 8*2

I actually think they detract from readability.

I'm sure there are sound reasons why shift has precedence over addition in C, but I find it counter-intuitive in the extreme.

Maybe a nice dose of online mockery will help me remember in the future :(

Note to non-geeks:
Don't worry, not much to see here. I made a school-boy error.

Date: 2010-07-13 10:39 am (UTC)
From: [identity profile] venta.livejournal.com
Yes, I finally managed to formalise my confusion as follows.

3 + 2*4 != 3+2<<2

Would you bracket

x = 3 + 2*4

?

Date: 2010-07-13 10:46 am (UTC)
From: [identity profile] bateleur.livejournal.com
Would you bracket x = 3 + 2*4?

Depends on the circumstances. I wouldn't in a case like:

position + 4*increment

...but I would for something like:

(width1 * height1 * depth1) + (width2 * height2 * depth2)

The approximate rule being something to do with the length of the resulting term rather than anything intrinsic to the mathematics. (Note also my use of spaces to imply the expected precedence, as you have done in some cases too.)

Date: 2010-07-13 10:48 am (UTC)
From: [identity profile] venta.livejournal.com
... so the fact that your natural defence would have saved you must rely on your viewing << in a different light from * ?

If I could remember not to treat it the same, I wouldn't be in this mess ;) As it is, my shift was a very short line, so just got spaces to clarify its intended operation.

Date: 2010-07-13 10:57 am (UTC)
From: [identity profile] bateleur.livejournal.com
For me I think it's more that the familiarity of ops involving only * and + make them an exception which don't say much about other cases. In particular, the fact that * (or 'x') is often elided in mathematical writing makes it more natural to me to write 8*foo than foo<<2.

Of course, this does mean I'm vulnerable to messing up the precedence of something like foo^2, but fortunately it both binds very tightly and is seldom used!

Profile

venta: (Default)
venta

December 2025

S M T W T F S
 123456
78910111213
14151617181920
212223 24252627
28293031   

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Dec. 27th, 2025 11:19 am
Powered by Dreamwidth Studios