What to do to make '_Generic('a', char : 1, int : 2) == 1' true

68 views Asked by At

Is there any way the compiler can set the type 'a' to char, instead of int. This makes the values of these expressions true:

sizeof('a') == 1

_Generic('a', char : true, default : false)

In gcc _Generic('a', char : true, default : false) == false

2

There are 2 answers

2
ikegami On

You can use (char)'a' instead of a.

sizeof( (char)'a' )   // 1
_Generic( (char)'a', char : true, default : false )  // true
0
Lundin On

The problem is that character constants in C are int, not char. This is a well-known flaw of the C language. One easy solution to the problem might be to compile a specific file as C++, then link the generated .o file with the rest of the C project.

Otherwise you'd have to invent your own custom notation through some mysterious macro, which is really NOT recommended. For example:

#include <stdio.h>

#define CH(c) (#c [0])

int main (void)
{
  printf("%c %zu\n", CH(a), sizeof(CH(a)) );
}

Similarly, "a"[0] or *"a" will give the letter a of type char with size 1.

This will still allow hex escape sequences and the like, such as CH(\x61) to print a.