No, it is not possible to use scanf
to read an enum
type -- at least, not portably.
The problem is that you do not know how big the enum
is. So you don't know whether to use %d
or %hd
or %hhd
(or, perhaps, %u
or %hu
or %hhu
) to read the values.
If you write
scanf("%u", &stringy);
as in the question (and with the missing &
added), then scanf
is going to read a number and write it onto the stringy
variable, but it is going to assume that stringy
is an unsigned int
, occupying sizeof(unsigned int)
bytes of memory.
But if the compiler has decided that it can actually use a short int
or maybe even just a char
to hold enum numberByMonth
, this is going to overwrite memory, resulting in undefined behavior.
The OP said that "gcc told me it was an unsigned integer", and that may have been true on that day, but it won't necessarily be true on another day, or under a different compiler.
The safe way to fix this, although it's cumbersome, is to use a temporary variable which you can be sure of the size of:
unsigned int tmp;
scanf("%u", &tmp);
stringy = tmp;
It would also be possible to make the assumption that enums are always going to be int-sized (that is, to assume that the compiler is never going to make them smaller), but to protect that assumption with an assertion:
assert(sizeof(stringy) == sizeof(unsigned int));
scanf("%u", &stringy);
See also What is the size of an enum in C?