自学内容网 自学内容网

C语言——宏定义相关

宏定义函数

宏定义函数的参数无数据类型,可实现模板函数的功能
例如:

#define MAX(a, b) (a > b ? a : b)
std::cout << "max of a and b is: " << MAX(1, 2)  << std::endl;
std::cout << "max of a and b is: " << MAX(1.5, 2.1) << std::endl;

有一个技巧:利用do{}while(0) 包裹宏定义函数代码,这样能实现很复杂的宏定义函数,且能将该函数伪装成一个正常函数执行,例如:

#define UNIT_AREA(shape)               \
  do {                                 \
    if (shape == "circle") {           \
      std::cout << PI << std::endl;    \
    } else if ( shape == "square") {   \
      std::cout << "1" << std::endl;   \
    } else {                           \
      std::cout << "1.0" << std::endl; \
    }                                  \
  } while(0)
 
 std::cout << "area of unit area: " << std::endl;
 UNIT_AREA("circle");

常用宏定义函数收集

1、获取x的第bit位

#define __GET_BIT(x, bit) (((uint32_t)(x) & ((uint32_t)1 << bit)) >> bit)

2、设置x的第bit位

#define __SET_BIT(x, bit) ((x) = (uint32_t)(x) | ((uint32_t)1 << bit))

3、清零x的第bit位

#define __CLEAR_BIT(x, bit) ((x) = (uint32_t)(x) & ~((uint32_t)1 << bit))

原文地址:https://blog.csdn.net/phosphophylite/article/details/142653473

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!