为什么枚举数据类型总是在 c 中的 main() 之外声明?
Why is enum data type always declared out of main() in c?
为什么在 main() 函数外声明枚举数据类型?
如果我们在 main() 中声明枚举数据类型会发生什么?
枚举不必具有文件范围。可以在块作用域中声明枚举。
这是一个演示程序。
#include <stdio.h>
enum E1 { N = 10 };
int main(void)
{
int a[N];
enum E1 { N = 2 * N };
int b[N];
printf( "sizeof( a[] ) = %zu\n", sizeof( a ) );
printf( "sizeof( b[] ) = %zu\n", sizeof( b ) );
return 0;
}
它的输出是
sizeof( a[] ) = 40
sizeof( b[] ) = 80
考虑到根据 C 标准(6.2.1 标识符范围)
7 Structure, union, and enumeration tags have scope that begins just
after the appearance of the tag in a type specifier that declares the
tag. Each enumeration constant has scope that begins just after the
appearance of its defining enumerator in an enumerator list. Any
other identifier has scope that begins just after the completion of
its declarator.
通常,当枚举需要一个文件作用域时,即在多个函数中使用相同的枚举(例如在参数声明列表中)时,枚举在函数外部声明。
为什么在 main() 函数外声明枚举数据类型? 如果我们在 main() 中声明枚举数据类型会发生什么?
枚举不必具有文件范围。可以在块作用域中声明枚举。
这是一个演示程序。
#include <stdio.h>
enum E1 { N = 10 };
int main(void)
{
int a[N];
enum E1 { N = 2 * N };
int b[N];
printf( "sizeof( a[] ) = %zu\n", sizeof( a ) );
printf( "sizeof( b[] ) = %zu\n", sizeof( b ) );
return 0;
}
它的输出是
sizeof( a[] ) = 40
sizeof( b[] ) = 80
考虑到根据 C 标准(6.2.1 标识符范围)
7 Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator.
通常,当枚举需要一个文件作用域时,即在多个函数中使用相同的枚举(例如在参数声明列表中)时,枚举在函数外部声明。