enum,sizeof与宏

2012年5月8日 | 分类: 日志 | 标签: , , ,

项目里某个enum类型的值太多,我担心会超出存储限制(1Byte),然后想通过宏判断最大值是否超过限制

#if(TEST_ENUM_MAX > 255)
#error "..."
#endif

但是经测试发现即使超过编译也可以通过,上网搜索了一下发现:
C语言里的enum值、sizeof操作符都是在编译阶段处理的,宏(macro)是在预处理阶段(preprocessor)处理的,在编译阶段的前面,所以想通过宏去判断enum值或者sizeof操作结果肯定会有问题。用宏#define才可以实现条件编译。真是太坑爹了。

此文用于测试iPad上写博客,结论是打字很慢,尤其是敲代码太痛苦了。。。

updated:
使用下面测试代码编译:

#include 

typedef enum 
{
	TEST_ENUM_255 = 255,
	TEST_ENUM_256,
}TEST_ENUM;

int main()
{
	unsigned char c1,c2;
	c1 = TEST_ENUM_255;
	c2 = TEST_ENUM_256;
	printf("0x%02x,0x%02x\n", c1, c2);
	return 0;
}

#if (TEST_ENUM_256 == 0)
//#error "test"	//编译会报错,说明预处理阶段enum值当作0处理了
#endif

VC6.0编译结果:

D:\desktop\project\test\enum.c(13) : warning C4305: '=' : truncation from 'int ' to 'unsigned char '

enum.obj - 0 error(s), 1 warning(s)

cygwin gcc 3.4.4编译结果:

$ gcc -c enum.c
enum.c: In function `main':
enum.c:13: warning: large integer implicitly truncated to unsigned type

运行结果不用说也知道是0xff,0x00
可见编译器处理数据转换溢出的情况会报warning。另外测试enum类型sizeof的操作结果与int一致,都是4。

目前还没有任何评论.

[cusFace:84] [cusFace:83] [cusFace:82] [cusFace:79] [cusFace:67] [cusFace:66] [cusFace:65] [cusFace:54] [cusFace:53] [cusFace:52] [cusFace:51] [cusFace:50] [cusFace:49] [cusFace:48] [cusFace:47] [cusFace:44] [cusFace:43] [cusFace:42] [cusFace:41] [cusFace:40] [cusFace:39] [cusFace:38] [cusFace:37] [cusFace:36] [cusFace:35] [cusFace:34] [cusFace:33] [cusFace:32] [cusFace:31] [cusFace:30] [cusFace:29] [cusFace:28] [cusFace:27] [cusFace:26] [cusFace:25] [cusFace:24] [cusFace:23] [cusFace:22] [cusFace:21] [cusFace:20] [cusFace:19] [cusFace:18] [cusFace:17] [cusFace:16] [cusFace:15] [cusFace:14] [cusFace:13] [cusFace:12] [cusFace:11] [cusFace:10] [cusFace:09] [cusFace:08] [cusFace:07] [cusFace:06] [cusFace:05] [cusFace:04] [cusFace:03] [cusFace:02] [cusFace:01] [cusFace:00]