C++之宏定义实现两个数最值

转自:https://blog.csdn.net/baidu_33725271/article/details/69478782

方法一: 利用三重条件运算符

#include <stdio.h>
#define MIN(A,B) ( (A) > (B) ? (B) : (A) ) #define MAX(A,B) ( (A) > (B) ? (A) : (B) )
int main(void) { printf("%d\n",MIN(12,334)); printf("%d\n",MAX(12,334)); return 0; }


值得关注的是
1 . 宏定义的变量在引用的时候,用 ()括起来,防止预处理器展开的错误
2 . (a > b ? action1 : action2 ) 这样的方式和 if —else 结果一样,但他会使得编译器产生更优化的代码,这在嵌入式编程中比较重要。

方法二: typeof 关键字

#include <stdio.h>

#define MIX(X,Y) ({\
typeof(X) x_ = (X);\
typeof(Y) y_ = (Y);\
(x_< y_)? x_:y_;\
}) 
#define MAX(X,Y) ({\
typeof(X) x_ = (X);\
typeof(Y) y_ = (Y);\
(x_>y_)? x_:y_;\
})

int main(int argc, char const *argv[])
{
int num1,num2;

printf("input two numbers:");
scanf("%d %d",&num1,&num2);
printf("mix is %d,max is %d\n",MIX(num1,num2),MAX(num1,num2));
return 0;
}


值得借鉴的是

1 . typeof 关键字 用于获得变量的数据类型 。

2 . 宏定义的实现,用 { } 作为宏整体,里面是一个代码块,语句用 ; 隔开 。

3 . 当宏的实现长度很长的时候,使用换行符 \ 换到下一行 。

4 . 使用输入数据的类型定义局部变量 x_ 和 y_ 实现对原始数据的保护。

5 . 宏实现,不能用 ; 结尾

其他参考:https://zhidao.baidu.com/question/1703790750415801020.html

猜你喜欢

转载自www.cnblogs.com/Tang-tangt/p/9852885.html