Connecting Tech Pros Worldwide Forums | Help | Site Map

cascading increment operator in c++

Newbie
 
Join Date: Sep 2006
Posts: 2
#1: Sep 2 '06
#include<iostream.h>

void main()
{
int i = 10;

clrscr();
cout << i << i++ << ++i;
getch();
}

The output is
11 12 12

how these output is possible? plz give details explain

Newbie
 
Join Date: Jul 2006
Posts: 14
#2: Sep 2 '06

re: cascading increment operator in c++


The provided code will not produce the output you have given. The correct output should be:

(1) 10,original value, followed by,
(2) 10, the second value. Here, the ++ is executed after the insertion operator.

Now at the beginning of the third increment you will have 11.

(3) At this time, the ++ is executed before insertion operator works. so you will get 12.

In short the output should be 10 10 12.

BTW, what is the point of having getch here???
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,195
#3: Sep 2 '06

re: cascading increment operator in c++


Well I actually get 12 11 12

vmohanaraj I am afraid you are wrong in your explaination

The line of code

cout << i << i++ << ++i;

Invokes undefined behaviour, that is calling this line of code allows the compiler to do anything it wants to. This is because you have altered a single variable (i) more than once between sequence points.

There is no point trying to explain the output, it is very possible that it will be different on every platform that you try it on.
Newbie
 
Join Date: Jul 2006
Posts: 14
#4: Sep 4 '06

re: cascading increment operator in c++


Oops. It is really confusing. I really got 10 10 12, the way I thought it should be. So i went on explaining in that way. I am sorry for that.

However, what is the reason for the undefined behaviour? The statements are executed from left to right. I think that is true for << operator as well. That is why we get the output in that order. Therefore, is not it reasonable to expect that all of us should have got atleast 10 as the first number?
Newbie
 
Join Date: Sep 2006
Location: India
Posts: 14
#5: Sep 5 '06

re: cascading increment operator in c++


Banfa " Well I actually get 12 11 12" can you explain how this output is evaluated?

i got 12 11 11. i used a printf statement.

printf(" %d %d %d" ,i,i++,++i);
can you explain how the printf will be evaluated?
Newbie
 
Join Date: Aug 2006
Posts: 4
#6: Sep 5 '06

re: cascading increment operator in c++


I Thnk u guys are wrong

In c++, it works from right to left associativity.....thts why we get the answer as 121111

But in C, not in the way
Gunvant's Avatar
Newbie
 
Join Date: Sep 2006
Posts: 1
#7: Sep 5 '06

re: cascading increment operator in c++


The standard does not mandate any specific behaviour when you modify a
value twice between two sequence-points. Since no specific behaviour is
mandated, the behaviour you see is okay. Note however that that has
nothing to do with the increment-operator in particular.
Reply