A short post about using const in C++.

Consider the following 3 for-loops in C/C++:

/* Loop 1: */

for(int i = 0; i < getSomeValue(); ++i) { ...lots of stuff in here... }

/* Loop 2: */

int n = getSomeValue();

for(int i = 0; i < n; ++i) { ...lots of stuff in here... }

/* Loop 3: */

const int n = getSomeValue();

for(int i = 0; i < n; ++i) { ...lots of stuff in here... }

Best Practice: If the value of 'n' is not supposed to change throughout the lifetime of the loop, then I think everyone can agree that using const in Loop 3 is a best practice. This helps ensure that some other coder doesn't muck about with the loop's end condition inside the loop (since it will be flagged with a compiler error).

Optimization: It makes sense that, in general, Loop 2 would execute faster than Loop 1. But I was curious if a compiler could optimize Loop 3 to make it run faster than Loop 2? It's been awhile since I looked at any assembly output, and my compiler theory has always been rather weak, so I thought I'd throw the question out there in case anyone has a clue...

§424 · January 30, 2008 · C++, Software, Technology · · [Print]

4 Comments to “On The Merits Of Const…”

  1. Phil says:

    I did a little fiddling around at http://llvm.org/demo/index.cgi It’s a live web demo of the LLVM compiler. You can view the output of the compiler in the LLVM assembly language.

    There did not seem to be any difference in the performance of loop 2 and 3. I would guess that the const would help optimization is some cases though.

  2. Scott says:

    I would think a good compiler would recognize 2 and 3 are the same.

  3. David says:

    Hi Jeff,

    off topic : the new theme is really great. everything is smooth. and without javascript. And the source is clean. no hacks. It’s really good.

    I love the animations !


  4. Thanks David! I’ve also adapted a WordPress theme to match (completely) the website theme. I’ll be pulling that over pretty soon, once I figure out what to do with the WordPress sidebar…