C++ 条件运算符在全局函数中使用时无法正常工作

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

我正在尝试使用条件运算符来执行比较两个整数之间的值的简单 max/min 函数,但我发现当我在函数中全局使用这些条件运算符时,它们无法正常工作预期,但当我在本地放置完全相同的代码时,它们确实工作得很好。

在下面的代码中,我尝试了 4 种方法(如下面的注释所示),方法 2、3 和 4 都运行良好,但方法 1(使用相同的条件运算符在方法 4 中,但在全球范围内)只是没有产生正确的结果。

//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);}

您忘记了其中的 "return" 声明。需要指明函数返回的值。

你的编译器应该已经警告过你了。尤其是在学习C++的时候,把能想到的编译器诊断都打开是很有用的。每个称职的编译器都会抱怨这样的代码。