Chinaunix首页 | 论坛 | 博客
  • 博客访问: 968932
  • 博文数量: 200
  • 博客积分: 5011
  • 博客等级: 大校
  • 技术积分: 2479
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-27 15:07
文章分类

全部博文(200)

文章存档

2009年(12)

2008年(190)

我的朋友

分类:

2009-03-21 00:41:32

看到一段代码可以在编译期间查所在平台的类型大小是否是自己想要的大小的技术:
/** type verification section */


/**
 * Helper macro to verify a size at compile time.  If this fails, it will
 * produce a negative subscript compiler error.
 */

#define UC_VERIFY_SIZE(type, target_size) \
    typedef char __VERIFY_SIZE__##type[(sizeof(type) == (target_size)) ? 1 : -1]

/**
 * If any of these macros fails it means one of the typedefs in this file
 * does not match the proper size for this platform.
 */
UC_VERIFY_SIZE(uc_uint32, 4);
UC_VERIFY_SIZE(uc_sint32, 4);
UC_VERIFY_SIZE(uc_uint16, 2);
UC_VERIFY_SIZE(uc_uint8, 1);
UC_VERIFY_SIZE(uc_byte, 1);
UC_VERIFY_SIZE(uc_intptr, sizeof(void*));
UC_VERIFY_SIZE(uc_uintptr, sizeof(void*));

那个宏定义,定义了一个数组类型,数组类型的大小是又sizeof运算符和?:运算符构成的,这两个运算符因为操作的都是可以在编译期计算出来的量,因此可以在编译期完成数组类型定义,当大小并不是我们想要的时候,该数组的大小就是-1。会出现变异错误。
阅读(2817) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~