Can the type of the last argument before ...
in a variadic function be an enum type?
Do enum
types undergo default argument promotion?
There are some contexts where types that undergo default argument promotion cannot be used safely, with vararg handling (va_start
, va_arg
) being a notable example. The compilers I use seem to treat enum
types as an int
, which is safe to use in these contexts. Is this always the case? Can I safely use an enum type as the last argument before ...
in variadic functions?
CodePudding user response:
Yes, default argument promotion can happen depending on the underlying type chosen for an enum
.
From section 6.7.2.2 of the C standard regarding enumeration specifiers:
Each enumerated type shall be compatible with
char
, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration. The enumerated type is incomplete until immediately after the}
that terminates the list of enumerator declarations, and complete thereafter
So an implementation may choose to use a type smaller than int
as the underlying type, and if so then it is subject to default argument promotions. GCC in particular will do this if you specify the -fshort-enums
flag.
And if that's the case, you can't use that enum
as the last named argument in a variadic function. From section 7.16.1.4p4 regarding va_start
:
The parameter
parmN
is the identifier of the rightmost parameter in the variable parameter list in the function definition (the one just before the ,...
). If the parameterparmN
is declared with theregister
storage class, with a function or array type, or with a type that is not compatible with the type that results after application of the default argument promotions, the behavior is undefined.