How does the compiler work here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

class foo
{
private:
  static int count;
public:
  foo(){count++;}
  int getcount(){return ++count;}
};
//
int foo :: count = 0;
//
int main()
{
  foo f1, f2, f3, f4;
  cout<<"f1 count is "
  <<f1.getcount()<<endl;
  cout<<"f2 count is "
  <<f2.getcount()<<endl;
  cout<<"f3 count is "
  <<f3.getcount()<<endl;
  cout<<"f4 count is "
  <<f4.getcount()<<endl;
  
  return 0;
}


The output is:

5
6
7
8


1
2
3
4
5
6
7
8
9
  cout<<"f1 count is "
  <<f1.getcount()<<endl
  <<"f2 count is "
  <<f2.getcount()<<endl
  <<"f3 count is "
  <<f3.getcount()<<endl
  <<"f4 count is "
  <<f4.getcount()<<endl;
  return 0;

Now the output has been reversed!

8
7
6
5

Why??

Last edited on
1
2
3
4
5
6
7
8
cout<<"f1 count is "
<<f1.getcount()<<endl
<<"f2 count is "
<<f2.getcount()<<endl
<<"f3 count is "
<<f3.getcount()<<endl
<<"f4 count is "
<<f4.getcount()<<endl;
The behavior of this piece of code is undefined.

Another example:
1
2
int x = 0;
std::cout << x++ << ' ' << x++ << std::endl;
What do you think the output will be? Regardless of what answer you gave, it's wrong. With a few exceptions, the language doesn't specify the order of evaluation of expressions, so using multiple operations with side effects (e.g. increments, assignments, function calls) on a single object give undefined behavior.
Maybe you're right, helios, I tried your example, the output was arbitrary, but it's not the case in my example, it's the accurate output but reversed.
Yes, again: it's undefined. You're seeing the effects of undefined behavior. "Undefined" doesn't mean "random" or "nonsensical", it means that any behavior is permissible.
Last edited on
Yeah yeah ... I got you right now, actually I exprienced a combination of your example and it shown a very wierd results, some of it was wrong but also have some logic, thanks a lot for your great help!
Last edited on
Topic archived. No new replies allowed.