Last active
December 14, 2021 09:35
-
-
Save sutyum/cf28e06e4414758ca10eeaecc7bc7122 to your computer and use it in GitHub Desktop.
C macros beyond the usual examples
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
/* | |
A single '#' will create a string from the given argument, | |
regardless of what that argument contains, | |
while the double '##' will create a new token by concatenating the arguments. | |
*/ | |
/* Run with compiler flag `-E` using gcc to see the pre-processor output. */ | |
#ifdef ERR | |
#error "Hey! You've got a compile time error." | |
#endif | |
#define f(a,b) a##b | |
#define s(a) #a | |
#define PRINT_TOKEN(token) printf(#token " is %d\n", token) | |
#define BUILD_FIELD(name) my_struct.inner_struct.field_##name | |
#include <stdio.h> | |
typedef struct { | |
int field_age; | |
} inner_struct_t; | |
typedef struct { | |
inner_struct_t inner_struct; | |
} my_struct_t; | |
int main() { | |
int GET_A = 9; | |
printf("%d\n", f(GET_, A)); // 9 | |
printf("%s\n", s(GET_A)); // GET_A | |
// printf("%s\n", #GET_A); // Error | |
// printf("%d\n", GET_##A) // Error | |
PRINT_TOKEN(GET_A); // GET_A is 9 | |
my_struct_t my_struct = { | |
.inner_struct = { | |
.field_age = 45 | |
} | |
}; | |
PRINT_TOKEN(BUILD_FIELD(age)); // BUILD_FIELD(age) is 45 | |
return 0; | |
} | |
/* | |
Expected console output | |
----------------------- | |
9 | |
GET_A | |
GET_A is 9 | |
BUILD_FIELD(age) is 45 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment