Monday, May 27, 2013

What is wrong in the first code?

#include <iostream>

#define MAX(a,b) (a<b)? a:b
using namespace std;
int main(){
  int a = 5;
  int b = 10;
  cout << MAX(a, b);   // the result is 1, but I want it to be 5
return 0;
}


And I try the following, and it works. What is the reason?

#include <iostream>
#define MAX(a,b) ((a)<(b)? (a):(b))
using namespace std;
int main(){
  int a = 5;
  int b = 10;
  cout << MAX(a, b);   // the result is 5
return 0;
}

1 comment:

  1. Operator precedence. In your first example operator precedence rules expands it to:

    (cout << (a<b)) ? a : b

    and in the second example it expands to:

    cout << ((a < b) ? a : b)

    Because a<b equals true and that cout operator<< prints booleans as integers, the first example writes 1.

    ReplyDelete