+ 2

ques 1. int y = 5; cout<< ++y + y++; ques 2. int y = 5; cout<< y++ + ++y; how is it working?

output of 1 is 13 and output of 2 is 12

26th Aug 2016, 3:43 AM
Pahul Preet Singh
Pahul Preet Singh - avatar
7 Respuestas
+ 3
i explored Internet and i found that post increment has higher precedence than pre increment. I hope that's the correct explanation, if we apply this to questions the answers come correct.
26th Aug 2016, 7:03 AM
Pahul Preet Singh
Pahul Preet Singh - avatar
+ 2
in ques 1 ++y will be 5+1 as ++ increment are before. now ++y=6 then you are adding y to it as (++y +y)++ according to c++ so 6+6=12 then one ++ increment to the answer hence 13
26th Aug 2016, 6:36 AM
Kandarp Singh
Kandarp Singh - avatar
+ 2
but in ques 2 y++ will be treated as 5 becoz you are incrementing ++later then you are adding ++y as y has become 6 ++ before will make it 7 so answer is 5+7=12
26th Aug 2016, 6:39 AM
Kandarp Singh
Kandarp Singh - avatar
+ 2
This question baffles me.. Cheers to Mr Preet Singh for asking this...
30th Aug 2016, 12:13 PM
Lord Saahil
Lord  Saahil - avatar
+ 1
The question is really tricky and almost impossible to answer. The reason is behind the find of Pahul Preet Singh. Yes, precedence is a keypoint, meanwhile the implementation how precedence handled by compiler are differ from compiler to compiler. That's why the same code will outputs different results in different environments. For example, Sololearn has 13 and 12, MS Visual Studio 2015 has 12 and 12. To avoid this, it's recommended to not alter an output more than once in a statement. For example, use x = 1 + x except x = ++x.
28th Aug 2016, 11:32 AM
Tamas Szekffy
Tamas Szekffy - avatar
0
the result may be different depending on the compiler, and even may differ from version to version. Agree with Tamas to write clean code, not alter output more than once, and it may be confusing.
31st Aug 2016, 9:28 PM
vani malley
vani malley - avatar
- 1
No idea
26th Aug 2016, 5:52 AM
Khoi Nguyen Doan
Khoi Nguyen Doan - avatar