Ummm...I'm not a C++ Developer (well, at least not a real good one) ... but...

Published 28 May 03 11:12 PM | Joel Semeniuk

Why:

const int repeat = (1<<12);

and not

const int repeat = 4096;

Or is that just to ensure that us C#/VB developers go cross-eyed when debugging?

Comments

# Cory Smith said on May 29, 2003 09:03 AM:

You are aware that VB.NET 2K3 can do:

Public Const REPEAT As Integer = (1 << 12)

;-)

I'm not a fan of this either, but I think it comes from thinking of the variable as a bit value rather than a numeric value. So when it's set like this, it's simpler to see that bit 13 is set. Again, not that I agree with it, but I could see it.

# Neil Weber said on May 29, 2003 10:09 AM:

I was a C++ developer (and before that a C programmer) and did this all the time. I still do it in Java. Using the bitshift operator, we make the compiler figure out the correct number that corresponds to the bit we want. Relying on my math skills (especially for the higher bits) would be a mistake.

# Jesse Ezell said on May 29, 2003 11:14 AM:

Like Neil points out, it is to define a bit constant. You would never do this for a normal integer (like "int i = (1<<2)|(1<<7);" ). It makes the code a lot more readable:

#define HAS_COLOR (1)
#define HAS_MASK (1 << 1)
#define HAS_BACKGROUND (1 << 2)
#define HAS_BORDER (1 << 3)

Of course, if you wanted to be really readable, you could just make a macro:

#define BIT(x) (1 << x)

So, then you could write

#define HAS_COLOR BIT(0)
#define HAS_MASK BIT(1)
#define HAS_BACKGROUND BIT(2)
#define HAS_BORDER BIT(3)

But, I don't think I've ever seen anyone go through all the trouble to make a macro for this, since the readability gain isn't really that significant.

# Kate Gregory said on July 10, 2003 02:07 AM:

Ever written a loop because you want to time some code, but it runs too fast so instead of 100 times through the loop you decide to go 1000 times? And that's not enough so you try 10,000? But that takes too long so you go with 5000? It's not exactly elegant. If repeat (a very revealing variable name) is defined with the bitshift, you just tweak how many places you're shifting by till you get what you like.

And for the record, I didn't write that code :-)

Kate

# Huh said on July 26, 2004 03:11 AM:

what?

This Blog

Cool Places

Good Links to Eat

INETA and UG Links

Other Blogs

Syndication