Can you explain this please..

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
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.
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
Good call ne555 That might explain why he's seeing 2. There's a lesson in there for you OP.
Last edited on
@Computergeek01 it is not a typo..,please note carefully it is p++ & q++ not ++p & ++q....So it should give 0 but giving 2
@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
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.
@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
Topic archived. No new replies allowed.