The function does not change the value of the global variable

Mar 28, 2019 at 4:10am
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 Mar 28, 2019 at 4:10am
Mar 28, 2019 at 4:22am
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 Mar 28, 2019 at 4:26am
Mar 28, 2019 at 7:54am
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 Mar 28, 2019 at 8:01am
Mar 28, 2019 at 8:45am
Sub-expression evaluation order traditionally falls into the "unspecified" behaviour category.

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

Mar 28, 2019 at 4:30pm
Oh, so this is the reason.
Thank you very much, my friends: jonnin, Peter87, and salem c
Topic archived. No new replies allowed.