Repetitive calculations with sizeof, strlen, etc

Viewed 50

Let's say I have a large array and I'm doing something like the following:

for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i)
    printf("arr[%d]=%d\n", i, arr[i]);

Of course, the sizeof stuff shouldn't be calculated every time so it should be like this instead:

size_t len = sizeof(arr)/sizeof(arr[0]);
for (int i = 0; i < len; ++i)
    printf("arr[%d]=%d\n", i, arr[i]);

My questions is whether it can be assumed that any compiler will automatically do the above optimization and so it doesn't matter which approach I use? Or should I assume that that's not the case and the second approach is the only correct one.

1 Answers

There is no reason to hoist the division out of the loop condition. It isn't even a question of how many times the division is evaluated (as is the usual concern in these cases, and may require the compiler to use "escape analysis" to determine whether the length value can change between iterations). The simple fact is that sizeof(arr)/sizeof(arr[0]) is a constant expression which will be evaluated at compile time, and will be no different to if you hard-coded a number there.

Related