0

There is a Macro #define buried deep in the libraries that I would like to quickly know the exact value of. Is there a way to store the value of the definition into a String so I could print it?

#define intgr 12
#define bnry 0b00000001
#define hex 0x0A
#define str "Hello World"

String myStr;

myStr = intgr;
cout<< myStr << endl;  //Simple enough, work no problem
//12              <- actual
//12              <- expected

myStr = bnry; // using "bnry" would not work as #define does not touch inside quotes
cout<< myStr << endl;
//1               <- actual
//0b00000001      <- expected

myStr = hex;
cout<< myStr << endl;
//10               <- actual
//0x0A             <- expected

myStr = str;
cout<< myStr << endl;
//Hello World      <- actual
//"Hello World"    <- expected, must include the quotation
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Jake quin
  • 738
  • 1
  • 9
  • 25
  • 1
    whats wrong with `std::cout << str ;` ? – 463035818_is_not_an_ai Feb 14 '23 at 19:04
  • @463035818_is_not_a_number it does not include the quotation marks that is present in the #define statement, i would like to store all characters in the #define statement – Jake quin Feb 14 '23 at 19:06
  • fwiw, `std::cout << str;` does print the *value*. What you want to see actually is the literal that was used for the definition. – 463035818_is_not_an_ai Feb 14 '23 at 19:07
  • @463035818_is_not_a_number yes, im sorry could not explain it better, i do not know the correct words :) – Jake quin Feb 14 '23 at 19:08
  • no worries, I was just too impatient and didn't read carefully at first – 463035818_is_not_an_ai Feb 14 '23 at 19:09
  • C allows for different ways of representing a value, and the value -- not the source code representation -- is what's available to your program. If you want to find what's in the source file, use `grep`, e.g., `grep -R "#define.*CHAR_BIT" /Library/Developer/CommandLineTools/usr/include` – torstenvl Feb 14 '23 at 19:09

1 Answers1

5

You can use the well-known process of "stringizing" a pre-processor symbol, as shown below.

#include <stdio.h>

#define intgr 12
#define bnry 0b00000001
#define hex 0x0A
#define str "Hello World"

#define STRING(x) #x
#define STRINGIZE(x) STRING(x)


int main(void) {
    char* strintgr = STRINGIZE(intgr);
    char* strbnry = STRINGIZE(bnry);
    char* strhex = STRINGIZE(hex);
    char* strstr = STRINGIZE(str);
    
    printf("%s\n", strintgr);
    printf("%s\n", strbnry);
    printf("%s\n", strhex);
    printf("%s\n", strstr);
    
    return 0;
}

Link to IDEOne Code in C
Link to IDEOne Code in C++

P.S. I used C syntax and char* type, however, after the pre-processor macros, C++ output and string type should work just as well.

Output

12
0b00000001
0x0A
"Hello World"
abelenky
  • 63,815
  • 23
  • 109
  • 159