#include <stdio.h>
#include <stdlib.h>
enum gender {male, female};
int main () {
enum gender choice;
printf("Your gender: ");
scanf("%u", &choice);
switch(choice)
{
case male: printf("You're a man."); break;
case female: printf("You're a woman."); break;
default: printf("Try again.");
}
return 0;
}
It doesn't matter what i write to console, it shows me 'male' case, 'You're a man.'. I've tried to write case's with quotes and single quotes but it's not working. Can you help me? That's my first question here and also sorry for my English if i had any mistakes.
From the C Standard (6.7.2.2 Enumeration specifiers)
4 Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined,128) but shall be capable of representing the values of all the members of the enumeration.
It means that internally an object of an enumeration type is not necessary stored as an object of the type int or unsigned int. It can be stored internally as an object of the type char.
So this call of scanf
scanf("%u", &choice);
invokes undefined behavior.
You need to use an intermediate variable of the type unsigned int and after the call of scanf with this variable assign its integer value to the object choice.
Another approach is for example to declare an object of the type char and ask the user to enter either 'm' for male of 'f' for female After that you can convert it either to the value 0 or 1.
For example
char c = 0;
scanf( "%c", &c );
if ( c == 'm' ) c = 0;
else if ( c == 'f' ) c = 1;
else c = 2;
choice = c;