我想使用枚举作为函数返回类型或参数。但是当我按原样给出它时,它会给出错误消息。但是如果我键入相同的定义,它就可以正常工作。
#include <stdio.h>
enum // if *typedef enum* is used instead, it's working fine
{
_false,
_true,
} bool;
bool func1(bool );
int main()
{
printf("Return Value = %dnn", func1(_true));
return 0;
}
bool func1(bool status)
{
return status;
}
请帮助我理解这一点。谢谢。
你不是在创建一个新的类型bool
,而是在声明一个名为 bool
的变量。
此代码:
enum
{
_false,
_true,
} bool;
声明匿名枚举类型的变量bool
。 typedef enum { ... } bool;
定义了一个名为 bool
的类型,可用于引用枚举类型。
你也可以写
enum bool
{
_false,
_true,
};
但是您必须将类型称为 enum bool
. 最便携的解决方案是写入
typedef enum bool
{
_false,
_true,
} bool;
即定义一个名为 bool
的枚举类型和引用它的称为 bool
的通用类型。
你的语法错了。
如果您不使用typedef
那么它应该是这样的:
enum bool
{
_false,
_true,
};
enum bool func1(enum bool );
enum bool func1(enum bool status)
{
return status;
}
您使用的语法是错误的。按如下方式使用它。
#include <stdio.h>
enum bool // if *typedef enum* is used instead, it's working fine
{
_false,
_true,
} ;
enum bool func1(enum bool );
int main()
{
printf("Return Value = %dnn", func1(_true));
return 0;
}
enum bool func1(enum bool status)
{
return status;
}
相反,如果您使用 typedef,您可以直接使用 bool
而不是 enum bool
。
还要引用C99标准:
Section 7.16 Boolean type and values < stdbool.h >
1 The header <stdbool.h> defines four macros.
2 The macro
bool expands to _Bool.
3 The remaining three macros are suitable for use in #if preprocessing directives. They are
true : which expands to the integer constant 1,
false: which expands to the integer constant 0, and
__bool_true_false_are_defined which expands to the integer constant 1.
4 Notwithstanding the provisions of 7.1.3, a program may undefine and perhaps then redefine the macros bool, true, and false.
如果你有一个编译到 C99 标准的编译器,那么你只需要包含 stdbool.h
并使用像 bool b = true;
这样的 bool 。