noob needs help with ++ operator

Aug 31, 2013 at 12:14am
ok, i just need help understanding my compiler's methodology of analyzing this code. i know the "a++" increases the value of 'a' by 1. but i don't know why the following result is displayed. the answer comes out to be "7 6 7 5". what i was expecting was "7 7 7 7". in high school my professor told me that the compiler analyzes it from right to left, and then displays it from left to right. here's the code. i need step-to-step analysis. thanks in advance!

1
2
3
4
5
6
7
8
9
10
  #include<iostream>
  using namespace std;
  #define endp cin.ignore()
  int main()
  {
	int a=5;
        cout<<a<<endl<<a++<<endl<<a<<endl<<a++;
        endp;
	return 0;
  }
Aug 31, 2013 at 12:16am
You cannot [safely] modify a variable multiple times in the same statement like that. The behavior is undefined.

Try this:

1
2
3
4
5
cout<<a<<endl; // prints 5
cout<<a++<<endl; // prints 5
cout<<a<<endl; // prints 6
cout<<a++; // print 6
// at this point, a==7 
Aug 31, 2013 at 12:19am
thanks for the quick reply. thing is, i am aware that i can use the variable one cout statement at a time. i'm only curious as to why my code outputs what it outputs. any thoughts?
Aug 31, 2013 at 3:42am
i'm only curious as to why my code outputs what it outputs. any thoughts?


The rules of the C++ language do not explain the output.... the behavior is undefined. Looking for an answer is practically meaningless because the output can vary from compiler to compiler.

You might get "7 7 7 7"... or you might get "7 6 7 5" or you might get "1537 188993 48 0" or the program might crash. Literally anything can happen and still be within bounds of what the C++ language allows.


There is no deeper meaning. The only answer is "it's undefined"
Aug 31, 2013 at 11:19am
1
2
3
4
5
6
7
8
9
10
#include<iostream>
using namespace std;
#define endp cin.ignore()
int main()
{
    int a=5;
        cout<<++a<<endl<<a<<endl<<a<<endl<<++a;
        endp;
    return 0;
}
Last edited on Aug 31, 2013 at 11:47am
Aug 31, 2013 at 3:17pm
@Chriscpp:

That is also undefined.

If you modify a variable, you cannot read/modify it anywhere else on the same sequence point.
Aug 31, 2013 at 4:13pm
What Disch said.

SomeBook wrote:
Most operators do not specify the order in which operands are evaluated: The compiler is free to evaluate either the left -or right- hand operand first.


Now you see why using operators that cause side effects in the same statement are not so good, be it increment or decrement.
Last edited on Aug 31, 2013 at 4:14pm
Topic archived. No new replies allowed.