×

# Behavior of Increment Operators

Please guide me what'll be output of the following code segment in c++ if 'a' is initialized at 7.

 1 cout<

Moderator's Note: This kind of questions actually have no answer. Here’s why. In practice, avoid them

Note by Anweshan Bor
1 year, 5 months ago

Sort by:

Actually, coding like this is ambiguous and considered a bad idea · 1 year, 5 months ago

Yes totally agreed. · 1 year, 5 months ago

Answers explaining why this is not a good idea Quora and StackOverflow

@anweshan bor · 1 year, 5 months ago

The output should be $$7 \quad 8 \quad 9$$

When you use a++ operator it first prints the value of a then increments its value. so first the value of $$a = 7$$ gets printed then its value gets incremented to $$8$$. After this when you use the ++a operator, it first increments the value of $$a$$ then prints it so first the value to a is increased to 9 then it is printed.

In short the post increment operator (a++) increments the value of a after the command given to it while the pre increment operator (++a) first increments the value of a then it is used in the command given to it.

Hope it helps :) · 1 year, 5 months ago

I too thought of the same output but my compiler gave it out as '888'. Well, thank you for the views. · 1 year, 5 months ago

Cascading cout statements are initialized from right to left. Though as Agnishom mentioned, this isn't a good idea, such questions commonly come for Viva. · 1 year, 5 months ago

Well, it's worse than a bad idea. It is undefined.

Now that I am an ex-student, I should probably drop an email to our CS teacher. · 1 year, 5 months ago

Please cc to all Indian CS teachers. · 1 year, 2 months ago

Haha · 1 year, 2 months ago

I asked this from my CS teacher and she said that the output depended on which compiler we are using. Different compilers could give different output. Is it so?? · 1 year, 5 months ago

Read up on the link Agnishom posted · 1 year, 5 months ago

Actually the cascading took place from right to left as after postfix(++a) .It becomes the last updated value i.e 8 . So compiler starts reading the output from right to left. · 1 year, 5 months ago

The answer is : 7 8 8 · 1 year, 5 months ago

The answer is 888.. Bcoz cout has a right to left associativity... So the answer mostly depends on compailer...in right to left associative answer is 888... · 1 year, 5 months ago

Answer will be 888. · 1 year, 5 months ago