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

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?

3 Comments

  • 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.

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





    #define HAS_COLOR (1)


    #define HAS_MASK (1 &lt;&lt; 1)


    #define HAS_BACKGROUND (1 &lt;&lt; 2)


    #define HAS_BORDER (1 &lt;&lt; 3)





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





    #define BIT(x) (1 &lt;&lt; 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.





  • 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

Comments have been disabled for this content.