-3
#include<bits/stdc++.h>
#define MAX(A,B) (A>B)?A:B
using namespace std;

int main()
{
    int i= 1, j=2;
    int val1 = max(++i, ++j);
    cout<<"i : "<<i<<" j : "<<j<<endl;
    printf("Val2 : %d\n", val1);

    int k = 1, l = 2;
    int val2 = MAX(++k, ++l);
    cout << "k : " << k << " l : " << l << endl;
    printf("Val2 : %d\n", val2);

    return 0;
}

Output of the above code:

i : 2 j : 3

Val2 : 3

k : 2 l : 4

Val2 : 4

But I think it should be:

i : 2 j : 3

Val2 : 3

k : 2 l : 3

Val2 : 3

Could anyone please clarify it briefly?

  • 5
    OK, this cannot be java and python and c++ – KevinO Mar 14 '19 at 18:12
  • 1
    Please use the appropriate tag the distinguishes the language you're using. Python and Java are irrelevant to this. – Vasilis G. Mar 14 '19 at 18:13
  • 3
    Hint: manually expand the MAX macro. – Joseph Sible-Reinstate Monica Mar 14 '19 at 18:15
  • Try to expand the macro by hand and then think about what the expanded code does. – sepp2k Mar 14 '19 at 18:15
  • 3
    OT: [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Biffen Mar 14 '19 at 18:18
  • Because `MAX(++k, ++l)` is expanded using text substitution to `(++k > ++l) ? ++k : ++l` which increments either `k` or `l` twice. That formally gives undefined behaviour, BTW - any result is possible. – Peter Mar 14 '19 at 18:20
  • @max1000001 https://stackoverflow.com/questions/7432124/macros-and-postincrement – Peter Mar 14 '19 at 18:29
  • I think the UB in the link you posted stems from incrementing an argument to a function, which isn't the same as `int val2 = (++k > ++l) ? ++k : ++l` . I don't see why this expression causes UB. – max1000001 Mar 14 '19 at 18:48

1 Answers1

1

MAX here IS NOT a function. If it were a function then it would do what you are expecting it to do. But it is a macro, NOT a function. So MAX(++k, ++l) is not equivalent to ++k; ++l; MAX(k, l) but to (++k>++l)?++k:++l.

Hammerite
  • 21,755
  • 6
  • 70
  • 91