How to treat char as char in _generic in c

Viewed 155

I a working on designing a generic queue

https://github.com/Bhaumik-Tandan/Generic_queue_in_c

But i am facing a problem when I am creating a generic fucntion enqueue for all types of data types

#define enqueue(s,a) _Generic(a, int: enqueuei__19BIT0292, char*: enqueues__19BIT0292,double: enqueuef__19BIT0292,char:enqueuec__19BIT0292,float:enqueuef__19BIT0292)(s,a)

The bellow line treats 'c' as int and call the respective function.

enqueue(s,'c')

Whereas if I want to call function of char, I need to write

enqueue(s,(char)'c')

I know in C characters are internally treated as integers, but is there any way to tackle this, I don't want to write (char) in the brackets or create a new variable each time I pass a character

1 Answers

You can create a macro that tests if argument is a char (starts with ') like this:

#define is_char_literal(c) (#c[0] == '\'')

then you can use a ternal

#define enqueue(s,a) is_char_literal(a)? enqueuec__19BIT0292(s,a): __Generic(a, int: enqueuei__19BIT0292, char*: enqueues__19BIT0292,double: enqueuef__19BIT0292, char:enqueuec__19BIT0292, float:enqueuef__19BIT0292)(s,a)

and depend on the compiler, if your compiler supports optimization by "const" evaluation

Related