C语言 枚举实验
【摘要】有关c语言枚举类型的相关实验。
【目的】实验验证是否在预处理时进行替换。
// test.c预处理测试
enum Etype
{
A, // 未赋值的枚举值
B = 2 // 赋值的枚举值
};
# define C 3 // 宏定义
void main()
{
int a = A;
int b = B;
int c = C;
}
enum Etype
{
A, // 未赋值的枚举值
B = 2 // 赋值的枚举值
};
# define C 3 // 宏定义
void main()
{
int a = A;
int b = B;
int c = C;
}
笔者在Code Warrior下预处理,可以使用预处理指令来预编译这段代码——$ gcc -E test.c
预处理结果:
/* 2 */
enum Etype
/* 3 */ {
/* 4 */ A ,
/* 5 */ B = 2
/* 6 */ } ;
/* 9 */ void main ( )
/* 10 */ {
/* 11 */ int a = A ;
/* 12 */ int b = B ;
/* 13 */ int c = 3 ;
/* 14 */ }
/* 3 */ {
/* 4 */ A ,
/* 5 */ B = 2
/* 6 */ } ;
/* 9 */ void main ( )
/* 10 */ {
/* 11 */ int a = A ;
/* 12 */ int b = B ;
/* 13 */ int c = 3 ;
/* 14 */ }
可以看出,#define 定义的常量,在预处理的时候做了替换,而enum定义的常量,并没有进行替换。
补充一下,预处理只进行删除注释(//、/**/)、连接符(\)、预处理命令执行(#,##,#@)。
【目的】通过sizeof看枚举定义的变量所占的空间
# include <iostream >
using namespace std;
enum unsigned_char_e : unsigned char
{
}a;
enum signed_char_e : signed char
{
}b;
enum default_e
{
}c;
int main()
{
cout << sizeof(unsigned_char_e) << "\t" << sizeof( unsigned char) << "\t" << sizeof(a) << "\n" ;
cout << sizeof(signed_char_e) << "\t" << sizeof( signed char) << "\t" << sizeof(b) << "\n" ;
cout << sizeof(default_e) << "\t" << sizeof( int) << "\t" << sizeof(c) << "\n" << endl;
return 0;
}
编译成功,两个警告
enum unsigned_char_e : unsigned char
enum signed_char_e : signed char
范围枚举仅仅在C++0x标准或gnu++ox标准中使用
warning: scoped enums only available with -std=c++0x or -std=gnu++0x|
1 1 1
1 1 1
4 4 4
Process returned 0 (0x0) execution time : 0.433 s
Press any key to continue.
这种对枚举声明的变量限定空间大小的写法只在新标准C++中可用。
在C中编译不通过。