Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically replacing variables with #defines

I have a file with about 100 #defines in it, from 1-100, and each with a unique string value.

Now I'm trying to print this value, but instead of the value, I want to print what the #define is. For example:

#define FIRST_VALUE 1
var = FIRST_VALUE;
printf("%s", var);

and I want the printf to print FIRST_VALUE, not 1.

Is there any way to do this in C? Or must I just write out 100+ case blocks inside a switch statement?

like image 628
samoz Avatar asked Feb 16 '26 03:02

samoz


1 Answers

You can use stringification to achieve what you are looking for:

  #define FIRST_MACRO
  #define MACRO_TO_STRING(x) #x

  #include <stdio.h>

  main() {
     printf("%s\n",  MACRO_TO_STRING(FIRST_MACRO));
  }

This program will output:

FIRST_MACRO
like image 128
David Segonds Avatar answered Feb 17 '26 20:02

David Segonds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!