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

时间:2016-03-15 00:47:52

标签: c++ conditional-operator

我试图使用条件运算符来执行比较两个整数之间的值的简单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;
}

1 个答案:

答案 0 :(得分:3)

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

你忘记了&#34;返回&#34;在那里的声明。需要指出函数返回的值。

您的编译器应该已经警告过您。特别是在学习C ++时,打开您能想到的所有编译器诊断非常有用。值得拥有的每个编译器都会抱怨这样的代码。