关于在C语言中,用#define实现宏

关于在C语言中,用#define实现宏,第1张

在C语言中 #define 的主要作用: 1. 定义标识符常量 2. 定义宏 定义宏,例:
#define MALLOC(num ,type)  (type*)malloc(num*sizeof(type))
//
//      int*p = (int*)malloc(10 * sizeof(int));
//      int*p2 = MALLOC(10, int);
//      p == p2

宏的题例1:

写一个宏,可以将一个整数的二进制位的奇数位和偶数位交换。

#include 

#define SWAP(num) (num = ((num & 0x55555555)<<1) + ((num & 0xaaaaaaaa)>>1))

//0x55555555    01010101 01010101 01010101 01010101    分别取得 奇数位和偶数位的 1
//0xaaaaaaaa    10101010 10101010 10101010 10101010
int main()
{
        int num = 10;
        //00000000 00000000 00000000 00001010  交换前
        //00000000 00000000 00000000 00000101  交换后
        SWAP(num);
        printf("%#x\n", num);  //输出0x5  00000101
        return 0;
}

宏的题例2:

写一个宏,计算结构体中某变量相对于首地址的偏移。

#include 
struct S
{
        int a;
        char c;
        double d;
};

#define  OFFSETOF(st_type, mem_name)  (size_t)&(((st_type*)0)->mem_name)

//假设首地址就是从0开始的,那可以把0强转为st_type*, 指向成员men_name,
//然后把指向的地址进行& 取地址 *** 作,最后强转为size_t类型,就可以打印出相对应的偏移地址位置
int main()
{
        printf("%d\n", OFFSETOF(struct S, a)); //0
        printf("%d\n", OFFSETOF(struct S, c));  //4
        printf("%d\n", OFFSETOF(struct S, d));  //8
        return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/915000.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存