Created
May 8, 2017 20:39
-
-
Save zerolx/f5b0ab0d3d8fcb1e27b5a169f250ea1b to your computer and use it in GitHub Desktop.
Variable type discover in C99 way without _generic with just a simple macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Includes for the types and the I/O of main function | |
#include <stdio.h> | |
#include <stddef.h> | |
#include <stdint.h> | |
// The type discovery macro | |
#define typename(x) (__builtin_types_compatible_p(__typeof__(x), long int)) ? "long int" : \ | |
(__builtin_types_compatible_p(__typeof__(x), char *)) ? "pointer to char" : \ | |
(__builtin_types_compatible_p(__typeof__(x), char)) ? "char" : \ | |
(__builtin_types_compatible_p(__typeof__(x), _Bool)) ? "_Bool" : \ | |
(__builtin_types_compatible_p(__typeof__(x), short int)) ? "short int" : \ | |
(__builtin_types_compatible_p(__typeof__(x), int)) ? "int" : \ | |
(__builtin_types_compatible_p(__typeof__(x), long int)) ? "long int" : \ | |
(__builtin_types_compatible_p(__typeof__(x), long long int)) ? "long long int" : \ | |
(__builtin_types_compatible_p(__typeof__(x), float)) ? "float" : \ | |
(__builtin_types_compatible_p(__typeof__(x), long double)) ? "long double" : \ | |
(__builtin_types_compatible_p(__typeof__(x), void *)) ? "pointer to void" : \ | |
(__builtin_types_compatible_p(__typeof__(x), unsigned char)) ? "unsigned char" : \ | |
(__builtin_types_compatible_p(__typeof__(x), signed char)) ? "signed char" : \ | |
(__builtin_types_compatible_p(__typeof__(x), unsigned short int)) ? "unsigned short int" : \ | |
(__builtin_types_compatible_p(__typeof__(x), unsigned int)) ? "unsigned int" : \ | |
(__builtin_types_compatible_p(__typeof__(x), unsigned long int)) ? "unsigned long int" : \ | |
(__builtin_types_compatible_p(__typeof__(x), unsigned long long int)) ? "unsigned long long int" : \ | |
(__builtin_types_compatible_p(__typeof__(x), double)) ? "double" : \ | |
(__builtin_types_compatible_p(__typeof__(x), int *)) ? "pointer to int" : "other" | |
// The test main function | |
int main(){ | |
size_t s; ptrdiff_t p; intmax_t i; int ai[3] = {0}; // Types to test (the custom types is reducted to the base | |
// Result | |
return printf("%20s is '%s'\n%20s is '%s'\n%20s is '%s'\n%20s is '%s'\n%20s is '%s'\n%20s is '%s'\n%20s is '%s'\n%20s is '%s'\n", | |
"size_t", typename(s), "ptrdiff_t", typename(p), | |
"intmax_t", typename(i), "character constant", typename('0'), | |
"0x7FFFFFFF", typename(0x7FFFFFFF), "0xFFFFFFFF", typename(0xFFFFFFFF), | |
"0x7FFFFFFFU", typename(0x7FFFFFFFU), "array of int", typename(ai)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment