Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Enum usage with switch-case in C
#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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!