Can you explain this please..

Feb 6, 2015 at 4:00pm
please explain that why this program will give output of 2...According to me, it should give 0

1
2
3
4
5
6
7
8
#include <iostream>
#define prod(a, b) ((a > b)? a*a : b*b)

int main(){
int p = 0, q = -1;
std::cout << prod(p++, q++) << std::endl;
return 0;
}
Last edited on Feb 6, 2015 at 4:03pm
Feb 6, 2015 at 4:23pm
2? Is that a typo? The reason you're getting 1* is that the variables would be increamented before they get compared. So basically order of operations: http://en.cppreference.com/w/cpp/language/operator_precedence

*: There is no way you should be getting 2 here, 1 * 1 is 1.
Feb 6, 2015 at 4:26pm
macros are simply text substitution
so in your case it translates to ( (p++ > q++)? p++*p++: q++*q++ )
which invokes undefined behaviour http://en.cppreference.com/w/cpp/language/eval_order
Feb 6, 2015 at 4:33pm
Good call ne555 That might explain why he's seeing 2. There's a lesson in there for you OP.
Last edited on Feb 6, 2015 at 4:33pm
Feb 6, 2015 at 4:47pm
@Computergeek01 it is not a typo..,please note carefully it is p++ & q++ not ++p & ++q....So it should give 0 but giving 2
Feb 6, 2015 at 4:50pm
@ne555 thanks..that solved the prob..;)...but can you please explain the compiler schema to take a call on it...I am using gcc..Moreover why c++ shell in cplusplus.com is giving me 1
Last edited on Feb 6, 2015 at 4:52pm
Feb 6, 2015 at 5:02pm
Moreover why c++ shell in cplusplus.com is giving me 1

This is what is meant by undefined behavior. You're using some component of the language in a way that it wasn't intended. So the standard doesn't dictate what the outcome would be.
Feb 6, 2015 at 5:22pm
@Computergeek01 No I mean almost every compilers that I use gcc, clang or even VC++, it gives me 2...then why C++ shell gives me 1 in cplusplus.com
Feb 6, 2015 at 5:35pm
Topic archived. No new replies allowed.