简体   繁体   English

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

[英]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. 我试图使用条件运算符来执行简单的max / min函数,该函数将两个整数之间的值进行比较,但是我发现,当我在函数中全局使用这些条件运算符时,它们不能按预期方式运行,但它们可以正常工作当我将完全相同的代码放在本地时。

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. 在下面的代码中,我尝试了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);}

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. 特别是在学习C ++时,打开您可以想到的所有编译器诊断很有用。 Every compiler worth it's salt would've complained about code like this. 每个值得付出的编译器都会抱怨这样的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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