Unable to deduce the output | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

Unable to deduce the output

#include <iostream> using namespace std; int main() { int n=20,a; a=++n+n++; cout<<a; } What's the way of proceeding such questions?

23rd Jul 2017, 8:41 PM
Dipanjan Deb
Dipanjan Deb - avatar
5 Respostas
+ 4
Normally, you'd think it should be 42: a = (n+1)20+21(n+1) and after that n should equal 22. And while the latter is true - n =22 indeed, those kind of statements get tricky depending on the compiler version. Sololearn's one treats it like: 20(+1)+21(+1) ==> 21+22 ==> 43 This is why it is generally recommended to avoid mixed pre/post increment operation statements.
23rd Jul 2017, 9:27 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 3
43 and 43 on *all* compilers. Now ++n and n++ are *not* the same precedence. ++n is pre-increment a n++ is post. Precedence is ++n before all operations. So: a = ++n + n++; a = 21 + n++; (++n is pre-inc so n is 21 before all else) Now that's out the way, the rest is common sense. Either: a = (21 + 21)++; a = 42++; a = 43; Or a = 21 + 21++; a = 21 + 22; a = 43 This case will not be compiler-dependent. But there are plenty similar cases that will. In this case it matters not since all compilers obey pre-inc. But FYI, even if it didn't, L-R rules kick in. Left to Right Rule: a = ++n+n++; a = 21+21++; a = 42++; a = 43; See? On a final note, these questions crop up a lot and they really don't represent real life problems since most sane people will use parenthesis if for no other reason than code readability. (Parenthesis) are your friends.
23rd Jul 2017, 10:48 PM
Jamie
Jamie - avatar
+ 1
First of all tell me which language you are using to write above programme.
23rd Jul 2017, 8:46 PM
W.H.J.Hirushan
W.H.J.Hirushan - avatar
0
@WHJ Its in CPP
23rd Jul 2017, 8:49 PM
Dipanjan Deb
Dipanjan Deb - avatar
0
I once read the results of this kind of incrementation depends on the compiler.
23rd Jul 2017, 9:21 PM
Drax
Drax - avatar