Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda