C 当我将typedef enum用作函数返回类型或参数时,为什么要使用它
我想使用enum作为函数返回类型或参数。但当我按原样给出它时,它给出了错误信息。但是如果我使用相同的typedef,它就可以正常工作了C 当我将typedef enum用作函数返回类型或参数时,为什么要使用它,c,enums,C,Enums,我想使用enum作为函数返回类型或参数。但当我按原样给出它时,它给出了错误信息。但是如果我使用相同的typedef,它就可以正常工作了 #include <stdio.h> enum // if *typedef enum* is used instead, it's working fine { _false, _true, } bool; bool func1(bool ); int main() { printf("Return Va
#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 = %d\n\n", func1(_true));
return 0;
}
bool func1(bool status)
{
return status;
}
#包括
enum//如果改用*typedef enum*,则工作正常
{
_假,,
_是的,
}布尔;
布尔函数1(bool);
int main()
{
printf(“返回值=%d\n\n”,func1(_true));
返回0;
}
布尔函数1(布尔状态)
{
返回状态;
}
请帮助我理解这一点。谢谢。您的语法错了 如果您没有使用
typedef
,则应该是:
enum bool
{
_false,
_true,
};
enum bool func1(enum bool );
enum bool func1(enum bool status)
{
return status;
}
您不是在创建一个新类型bool
,而是在声明一个名为bool
的变量,该代码:
enum
{
_false,
_true,
} bool;
声明匿名枚举类型的变量bool
<代码>类型定义枚举{…}bool定义一个名为bool
的类型,可用于引用枚举类型
你也可以写
enum bool
{
_false,
_true,
};
但是您必须将该类型引用为enum bool
。最可移植的解决方案是编写
typedef enum bool
{
_false,
_true,
} bool;
i、 e.定义名为
bool
的枚举类型和引用它的名为bool
的常规类型。您使用的语法是错误的。使用它如下
#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 = %d\n\n", func1(_true));
return 0;
}
enum bool func1(enum bool status)
{
return status;
}
如果您有一个编译成C99标准的编译器,那么您可以只包含stdbool.h
并使用bool likebool b=true
仅提及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.