Reputation: 1064
I want to use enum as function return type or as a argument. But when I give it as is, it's giving error message. But if I typedef the same, it's working fine.
#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;
}
Please help me understand this. Thank you.
Upvotes: 0
Views: 1270
Reputation: 2335
Syntax you have used is wrong. Use it as below.
#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;
}
Instead if you use typedef you can directly use bool
instead of enum bool
.
Also to quote C99 standard:
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.
If you have a compiler which compiles to C99 standard then you can just include stdbool.h
and use bool like bool b = true;
.
Upvotes: 1
Reputation: 53047
You've got the syntax wrong.
If you're not using typedef
then it should be this:
enum bool
{
_false,
_true,
};
enum bool func1(enum bool );
enum bool func1(enum bool status)
{
return status;
}
Upvotes: 4
Reputation: 157364
This code:
enum
{
_false,
_true,
} bool;
declares a variable bool
of an anonymous enum type. typedef enum { ... } bool;
defines a type called bool
that can be used to refer to the enum type.
You can also write
enum bool
{
_false,
_true,
};
but then you have to refer to the type as enum bool
. The most portable solution is to write
typedef enum bool
{
_false,
_true,
} bool;
i.e. defining an enum type called bool
and a general type called bool
that refers to it.
Upvotes: 4
Reputation: 409196
You are not making a new type bool
, instead you are declaring a variable named bool
.
Upvotes: 4