Does condition of for loop calculate for every run?

When I make a loop that uses a function in a condition, such as:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int a;
    cin >> a;
    for(int i = 0; i < sqrt(a); i++){
    //...
    }
}


Is the function sqrt() in condition called for every single run of the loop, or does its value store somewhere just to be compared to i?
Last edited on
If a does not change inside loop, compiler knows what sqrt from standard library is, then it is possible that it would be evaluated only once.
Clang is smart enough to move square root evaluation outside the loop, when gcc leaves it inside (and it still only single instruction anyway).
You can check this yourself:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cmath>

using namespace std;

int x(int y)
{
    cout << "x";
    return y;
}

int main()
{
    int a;
    cin >> a;
    for(int i = 0; i < x(a); i++){
    //...
    }
}
5 xxxxxx
@coder777 Your example is not entirely correct, as compiler has no right to eliminate function call in this case (as it contains a sideeffect which cannot be eliminated without changing visible program behavior).
condition-expression is calculated each iteration by standard, but compiler might optimise it if it will not change program behavior. In general it is better to save result of non-trivial function into variable and not rely on compiler-dependend behavior.
1
2
3
4
5
6
    {
        double end = sqrt(a);
        for(int i = 0; i < end; ++i) {
            //...
        }
    }
I don't see what's wrong with this code since the output shows that x is called each iteration (6 times) and it's a real program output.

When the compiler knows that there is no side effect it can optimize it of course.
Topic archived. No new replies allowed.