// 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).
> 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.