Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C enumerated types name scoping

Tags:

c

enums

GCC tells me you can't use the same names for separate enumerated type values, e.g.

enum flag_one {
    SUCCESS,
    FAIL
}

enum flag_two {
    SUCCESS,
    FAIL
}

is not allowed by the compiler. So scoping is not 'witihin' the enum definition?

Is the approach to do something like:

enum flag_one {
    FLAG_ONE_SUCCESS,
    FLAG_ONE_FAIL
}

enum flag_two {
    FLAG_TWO_SUCCESS,
    FLAG_TWO_FAIL
}

Slightly confused as I like using enums for return integer codes as its more readable/descriptive but I'm already starting to get name clashes

like image 441
bph Avatar asked Jan 16 '23 15:01

bph


1 Answers

So scoping is not 'witihin' the enum definition?

No. This is not allowed. Enumerator lists define constants. Your enums happen to be in the same scope -- the file scope. You cannot have two constants with the same name within the same scope.

From the draft of CX:

6.7.2.2 Enumeration specifiers

Semantics

3 The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted.127) [...]

Also, from footnote 127 (which is technically non-normative and for informational purposes only):

127) Thus, the identifiers of enumeration constants declared in the same scope shall all be distinct from each other and from other identifiers declared in ordinary declarators.

.

Slightly confused as I like using enums for return integer codes [...]

Use EXIT_SUCCESS and EXIT_FAILURE defined in stdlib.h.

like image 160
dirkgently Avatar answered Jan 29 '23 19:01

dirkgently