Why parentheses are needed

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
brianfry713
Guru
Posts: 5947
Joined: Thu Sep 01, 2011 9:09 am
Location: San Jose, CA, USA

Why parentheses are needed

Post by brianfry713 » Thu Jan 17, 2013 1:09 am

I'm explaining why this code won't work as you might expect:

Code: Select all

#include <iostream>
using namespace std;
#define max(a,b) a>b?a:b
#define max(a,b) a<b?a:b

int main() {
  int a=7, b=5, c=3;
  cout << (min(a,max(b,c))) << endl;
  return 0;
}
This prints 7, not 5 as it would if the defines are replaced with:
#define max(a,b) (a>b?a:b)
#define max(a,b) (a<b?a:b)

If you compile g++ with the -E option, you can see the output of the preprocessor:
cout << (a<b>c?b:c?a:b>c?b:c) << endl;
with values:
cout << (7<5>3?5:3?7:5>3?5:3) << endl;
The < and > associate left to right and have a higher precedence than ?: so this becomes:
cout << (0>3?5:3?7:1?5:3) << endl;
cout << (0?5:3?7:1?5:3) << endl;
The ?: associates right to left:
cout << (0?5:3?7:5) << endl;
cout << (0?5:7) << endl;
cout << (7) << endl;
Check input and AC output for thousands of problems on uDebug!

Post Reply

Return to “C++”