Shao Miller
7/8/2011 2:51:00 AM
On 7/7/2011 21:16, Lew Pitcher wrote:
> In alt.os.linux, I just encountered a post regarding debugging of a C
> program (source supplied). I won't trouble the group with the code in
> question, but I do have a question of my own about the code.
>
> The programmer had written something like...
>
> typedef enum { false, true } bool;
>
> int TheFunction(argument)
> int argument;
> {
> int inword;
>
> inword = true;
> /* other logic followed */
> }
>
> Is this use of an enum constant valid? To me, the enum shouldn't
> "exist" in that it acts like a "template" courtesy of the typedef. Had
> the author included a
> bool something;
> then the enum would, in my mind, "exist" wrt the code at hand.
>
> What do the C experts here think? Am I wrong to be suspicious of the
> OP's typedef and code, or is this really valid C? (Note that both the
> original code and my subset example above were coded in K&R C).
There's no 'bool' nor 'true' nor 'false' in "ANSI C," that I know of.
If that's the conformed-to Standard, then this seems fine.
I believe that 'false' and 'true' will be the 'int' values '0', and '1',
respectively.
The 'bool' type could be any implementation-defined integer type, I
think. 'unsigned char' might be handy, given these values, but there's
no obligation.
I'd be a bit worried about this code being compiled by a C99-conforming
[mode] implementation if <stdbool.h> was included. That header
'#define's 'bool' to '_Bool', 'false' to '0', 'true' to '1'.
One can use tag-less enums to produce 'int' constants in general, as far
as I know.
enum {
foo = 42,
bar = 13,
zero = 0
};
An odd pattern might be:
/** my_func: Blah blah blah... */
enum {
/* Return codes */
status_success,
status_out_of_memory,
status_invalid_parameter,
status_not_supported,
status_unknown_error
} my_func(
/* Parameters */
void * ptr
) {
/* Function body... */
return status_success;
}