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

135
Visualizações
Declaración de cambio de C y conversión explícita de enumeración

Vi muchas preguntas similares, pero ninguna responde a mi pregunta aquí: supongamos que tengo una Property de enumeración:

 enum { PROP_A = 1, PROP_B, N_PROPERTIES } Property;

Cuando trato de usarlo en una declaración de cambio como esta:

 // file test.c enum { PROP_A = 1, PROP_B, N_PROPERTIES } Property; int main(void) { int a = 0; switch ((Property) a) { case PROP_A: break; case PROP_B: break; default: break; }; return 0; }

El compilador arroja este error:

 test.c: In function 'main': test.c:11:20: error: expected ')' before 'a' 11 | switch ((Property) a) | ~ ^~ | )

¿Qué está mal con este código? Como referencia, en la documentación de GObject tienen este fragmento:

 typedef enum { PROP_FILENAME = 1, PROP_ZOOM_LEVEL, N_PROPERTIES } ViewerFileProperty; static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, }; static void viewer_file_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { ViewerFile *self = VIEWER_FILE (object); switch ((ViewerFileProperty) property_id) { case PROP_FILENAME: g_free (self->filename); self->filename = g_value_dup_string (value); g_print ("filename: %s\n", self->filename); break; case PROP_ZOOM_LEVEL: self->zoom_level = g_value_get_uint (value); g_print ("zoom level: %u\n", self->zoom_level); break; default: /* We don't have any other property... */ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } }

Que es esencialmente lo mismo. Por lo tanto debe ser posible. ¿Qué tiene de malo mi versión?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

En esta declaración

 enum { PROP_A = 1, PROP_B, N_PROPERTIES } Property;

declaró una Property de objeto de un tipo de enumeración sin nombre.

Así que en la declaración de cambio

 switch ((Property) a)

está utilizando expresiones sintácticamente incorrectas con dos objetos Property a .

parece que te refieres

 typedef enum { PROP_A = 1, PROP_B, N_PROPERTIES } Property;

Preste atención que usted puede simplemente escribir

 switch ( a )

En C, los enumeradores tienen el tipo int . Es decir, estos enumeradores PROP_A, PROP_B, N_PROPERTIES tienen el tipo int . Entonces, la conversión que intentó aplicar (si la enumeración se declarara correctamente) es redundante.

over 4 years ago · Santiago Trujillo Relatório

0

Supongamos que tengo una propiedad enum:

 enum { PROP_A = 1, PROP_B, N_PROPERTIES } Property;

Su código no define Property como un tipo de enumeración. Lo declara como una variable cuyo tipo es un tipo de enumeración sin etiquetar. Los operadores Typecast deben construirse a partir de tipos, no de variables, por lo que (Property) a no es válido.

Ese elenco también es innecesario . Una forma de resolver el problema sería simplemente dejarlo:

 switch (a) { case PROP_A: break; case PROP_B: break; default: break; }

Alternativamente, si quiere definir Property como un alias de tipo, entonces esa es la función de typedef :

 typedef enum { PROP_A = 1, PROP_B, N_PROPERTIES } Property;

Personalmente, sin embargo, no soy un fanático de typedef . Tiene algunos buenos usos, pero tiende a aplicarse mucho más allá de esos. Si quisiera declarar un tipo de enumeración al que pudiera hacer referencia además de su declaración, incluiría una etiqueta:

 enum property { PROP_A = 1, PROP_B, N_PROPERTIES }; int main(void) { int a = 0; switch ((enum property) a) { case PROP_A: break; case PROP_B: break; default: break; } return 0; }

(El elenco se incluye con fines demostrativos; sigue siendo innecesario).

over 4 years ago · Santiago Trujillo Relatório

0

Debe agregar typedef antes de enum para identificar la Property como un tipo. En el otro ejemplo que proporcionó para comparar, se usa typedef .

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