Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda