1

I came across this code while doing random search and I though to execute it on www.ideone.com and the output came 0 while I was expecting it to be 10.

#include <iostream>
using namespace std;

int main() {


    int count = 0; 
for(int i=0; i < 10; ++i) 
 count = count++; 

std::cout << count; 
    return 0;
}

As far as my understanding is, count = count++; can be assumed as count = count; and count = count + 1; So shouldn't the output be 10 instead of 0?What is the reason for such a behaviour?

NOTE: As pointed out by comments here that this question comes under "Undefined Behavior and Sequence Points", I want to just make it clear that as I am new to C++, I didn't knew that these are undefined behavior.So, I hope everyone will forgive for mistake.

user2916886
  • 847
  • 2
  • 16
  • 35
  • Have you tried count = ++count; ? (not tested) The side where the ++ is determines how the increment is asigned. – Broken_Window Mar 04 '14 at 23:08
  • @Yelinna, That's also UB pre-C++11. – chris Mar 04 '14 at 23:11
  • @Paranaix as I am new to C++, I didn't knew that it comes under Undefined Behavior and Sequence points. Thanks for letting me know.I will read it. – user2916886 Mar 04 '14 at 23:12
  • In your can try and see what the output will be when you have count++ alone instead of count= count++... then you will find the difference. – user3256147 Mar 04 '14 at 23:16

4 Answers4

4

The line that is the problem is count = count++;. For a ridiculously detailed description of what is wrong, read Undefined behavior and sequence points.

Basically, you come to the problem of which evaluates first, the assignment to count from the = operator or the assignment to count from the ++ operator. If it evaluates the assignment from the ++ operator first, then you will get 0. If it evaluates the = before the assignment from the ++, then you will get 10.

Community
  • 1
  • 1
Graznarak
  • 3,626
  • 4
  • 28
  • 47
0

AFAIR this is an unspecified behaviour, the result may vary from compiler to compiler.

DmitryARN
  • 648
  • 3
  • 10
  • 1
    It is *Undefined* Behaviour, see [intro.execution]/15. But why downvote this answer? – dyp Mar 04 '14 at 23:09
-1

You can just use count++; and it will increment. count++; is equivalent to count = count + 1;

-1

When you do this:

count = count++; 

You have essentially created a new value for count at this point. The count++ on the right is now considered an rvalue and the new value of count is the last value that was in count++. i.e. 0

smac89
  • 39,374
  • 15
  • 132
  • 179