简体   繁体   中英

C++ Conditional Operators Do Not Work Properly When Used in Global Functions

I am trying to use conditional operators to do the simple max/min functions that compare the values between two integers, but I found out that when I use those conditional operators globally in functions, they do not work as expected, but they do work well when I put the exact same codes locally.

In the code below, I've tried 4 methods (as indicated by the comments below), and method 2, 3, as well as 4 all work well, yet method 1 (which uses the same conditional operators as in method 4, but globally) just does not yield the correct results.

//For method 1 to method 4, pick one and comment out the others.

#include <iostream>

//Method 1: Does not work, yields "1,1".
int max(int a, int b){(a) > (b) ? (a) : (b);}
int min(int a, int b){(a) < (b) ? (a) : (b);}

//Method 2: Works well, yields "2,1".
#define max(x, y) ((x) > (y) ? (x) : (y))
#define min(x, y) ((x) < (y) ? (x) : (y))

//Method 3: Works well, yields "2,1".
int max(int a, int b){if(a > b) return a; else return b;}
int min(int a, int b){if(a < b) return a; else return b;}

int main(void)
{
    int a = 1, b = 2;

//Method 4: Works well, yields "2,1".
int large = ((a) > (b) ? (a) : (b));
int small = ((a) < (b) ? (a) : (b));

    int large = max(a,b); //Comment out when using Method 4.
    int small = min(a,b); //Comment out when using Method 4.

    std::cout << large << "," << small << std::endl;

    return 0;
}
int max(int a, int b){(a) > (b) ? (a) : (b);}

You forgot a "return" statement in there. It is required to indicate the value returned from a function.

Your compiler should've warned you about this. Especially when learning C++, it is useful to turn on all compiler diagnostics that you can think of. Every compiler worth it's salt would've complained about code like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM