The function does not change the value of the global variable

Dear people, please answer me this question:
My program is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int c=0;
int fun()
{
    for(int i=1;i<=100;i++)
        c++;
    return c;
}
int main()
{
    std::cout<<fun()<<' '<<c;
}

Output: 100 0
Why, the func function cannot change the value of variable c?
Last edited on
or did it?

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

int c=0;
int fun()
{
    for(int i=1;i<=100;i++)
        c++;
    return c;
}
int main()
{
    std::cout<<fun()<<' '<<c;
    std::cout << " " << c;
}


100 0 100

c is changed. cout buffered the 0 before it changed. One of our experts on undefined behavior can comment, I am not great at that stuff. But its generally not good to modify something and print it in the same statement.
Last edited on
My understanding is that the output of the original program should be "100 100" since C++17. Before that I'm not sure if it's undefined behaviour or if the order is just unspecified. The rules are so complicated in this area that I wouldn't recommend writing code that relies on it.
Last edited on
Sub-expression evaluation order traditionally falls into the "unspecified" behaviour category.

Unless there is some spiffy new standard to change that, as Peter87 suggests.

Oh, so this is the reason.
Thank you very much, my friends: jonnin, Peter87, and salem c
Topic archived. No new replies allowed.