About the loop condition

In case of the following two for loop:
1
2
3
4
5
6
// case 1
for (int i = 0; i < n; i++)
    something;
// case 2
for (int i = 0; i <= n - 1; i++)
    something;

The above two cases are different in the conditions. What confuses me is if the runtime of the two cases are the same. In other words, whether the 'n - 1' in case 2 will be calculated for every 'i' or only calculated once.
Thanks for your help.
n - 1 is evaluated each time the condition is checked, but with an optimizing compiler I wouldn't expect much difference performance-wise.

Some quick testing with Compiler Explorer shows that GCC and Clang generates identical machine code for both loops while with MSVC there is a small difference (doesn't necessarily mean one of them is slower).

GCC https://godbolt.org/z/coTv79z4a
Clang https://godbolt.org/z/MvcrGMnKs
MSVC https://godbolt.org/z/nrzz3do9n
Last edited on
> whether the 'n - 1' in case 2 will be calculated for every 'i' or only calculated once.

Unless n is a volatile object, with optimisations enabled, there wouldn't be a performance difference.
One way would be for the optimiser to rewrite the second loop as the first one.

The "as-if rule" allows code transformations that do not change the observable behaviour of the program.
https://en.cppreference.com/w/cpp/language/as_if
Thanks for your answers which solve my confusion.
Topic archived. No new replies allowed.