18.用宏定义实现 得到两个数的最值

版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/82954843

使用两种宏定义的方法实现 得到两个数的最小值和最值


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

#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 . 宏实现,不能用 ; 结尾

猜你喜欢

转载自blog.csdn.net/Fly_as_tadpole/article/details/82954843
今日推荐