Loop counter and amp; pointers


I'm writing a small specialized C99 library for graphs and I often get loops of the form:

for(int i = 0; i < graph->nvertices; ++i) {
  // ...

I'm wondering if it's a good practice, especially in the case of tigh loop. At first I thought the compiler would be smart enough to look at 'graph->nvertices' only once instead of looking at it at every iteration, but it seems impossible as graph->nvertices could change inside the loop. Is is smarter and faster to write:

const int N = graph->nvertices;
for(int i = 0; i < N; ++i) {
  // ...

It seems faster as it doesn't need look at the pointer more than once, but it does require the creation of a new variable.

Note: I guess this is the kind of situation where it's nice to be able to read a little assembly code to see what the compiler is actually doing, if someone has a nice reference I'm open to suggestions.

Try using higher optimization settings, some compilers should be able to optimize that away for you. You can also iterate backwards, only initializing the counter with the expression:

for (int i = graph->nvertices; i >= 0; --i)

However, you're going to wreak havoc on cache performance. I think the method you suggested is most straightforward, which lends itself to be clear to the compiler and to the next person reading your code.