Chinaunix首页 | 论坛 | 博客
  • 博客访问: 319229
  • 博文数量: 57
  • 博客积分: 146
  • 博客等级: 入伍新兵
  • 技术积分: 769
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-29 14:57
文章分类
文章存档

2014年(39)

2013年(13)

2012年(5)

我的朋友

分类: C/C++

2014-06-10 16:24:02

文档:CERT C Programming Language Secure Coding Standard

1.宏的变量名加上括号()

点击(此处)折叠或打开

  1. #define CUBE(I) (I * I * I)
  2. int a = 81 / CUBE(2 + 1);
宏扩展后

点击(此处)折叠或打开

  1. int a = 81 / (2 + 1 * 2 + 1 * 2 + 1); /* evaluates to 11 */
在变量名加上括号问题得到解决:

点击(此处)折叠或打开

  1. #define CUBE(I) ( (I) * (I) * (I) )
  2. int a = 81 / CUBE(2 + 1)

2.注意像函数的宏代替函数。
下面的代码调用puts不会打印任何东西。

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #define puts(x)
  3. /* ... */
  4. puts("hello world!\n")

解决方式:使用()、#undef、extern

括号的方式:C99上说括号封闭函数名,函数的任何宏定义都会局部地禁止。

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #define puts(x)
  3. /* ... */
  4. (puts)("I'm a library call!\n")

#undef方式

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #define puts()
  3. #undef puts
  4. /* ... */
  5. puts("I'm a library call!\n")

extern方式

点击(此处)折叠或打开

  1. extern int puts(char const *s);
  2. /* ... */
  3. puts("I'm a library call!\n")

3.别使用标准头文件名作为文件名
如果一个与标准头文件同名的文件放置在头文件(included source files)的搜索路径中,其行为是未定义的。

阅读(325) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~