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

318
Vistas
How can I pass either type or value to _Generic()

The sizeof builtin can take either a type or an expression, and will return the appropriate value.

I'd like to build a macro that uses _Generic() expressions to do something similar. In particular, I'd like to be able to pass either a type name or a value as the parameter, just like sizeof.

As a trivial example, I can do something like this:

#define F(x)  _Generic((x)+0, int: 1, long: 2)

That works because (x)+0 can be either an arithmetic expression or a type cast.

  • (1)+0 -> 1+0 -> 1 -> int: 1
  • (long)+0 -> 0L -> long: 2

But that doesn't work when the type is struct Foo.

I could use composite literal syntax, with curly braces: (x){0} but that fails for literal values:

  • (long){0} - works
  • (struct Foo){0} - works
  • (1){0} - not so much. :-(

Is there some twisted C syntax horror that will permit the use of either type names or expressions in a _Generic-expression?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Your compound literal idea will work if you combine it with typeof. However, please note that typeof is a a GCC C language extension, so it might not work in every C compiler.

#include <stdio.h>

typedef struct Foo {
  int mx;
} Foo;

#define F(x) _Generic((typeof(x)){0}, \
  int: 1, \
  long: 2, \
  struct Foo: 3)

int main()
{
  printf("%d\n", F(0));         // 1
  printf("%d\n", F(int));       // 1
  printf("%d\n", F((long)0));   // 2
  printf("%d\n", F(long));      // 2
  printf("%d\n", F((Foo){1}));  // 3
  printf("%d\n", F(Foo));       // 3
}
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