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

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

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 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