1

I am expecting a value as 10 and 10 from below code but getting it as 11 10 as the output, not sure why. I also tried ++a instead of a++ and got the output as 11 11(I know how it worked). I want to demonstrate increment operator. I know that if I write a++ on first line and then print the value of a it will show me the incremented value. please advise what change should I make in the cout statement to get the output as 10 11.

void main()
{
int a = 10;
cout<<a<<" "<<a++;
}
Krishna
  • 35
  • 6
  • 4
    The order of evaluation of subexpressions in an expression is unspecified. In fact, I think your program exhibits undefined behavior, by way of two unsequenced operations reading and modifying the same scalar object. – Igor Tandetnik Sep 07 '17 at 15:04
  • simply dont write code like this. Even if you could figure out in what order it is executed, anybody reading the code would need to figure it out again to understand the code. If you want to print the value of `a` twice and increment it, thats `cout << a << a; a++;`. Unneccesarily reading and writing to the same variable in the same expression adds complexity for zero benefit – 463035818_is_not_an_ai Sep 07 '17 at 15:18
  • BTW, the return type for `main` is `void`. – Thomas Matthews Sep 07 '17 at 15:36

0 Answers0