Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

312
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!