简体   繁体   中英

Log the text of an expression and its result without C preprocessor

I use this macro in C/C++ very frequently:

#define MYLOG(x) (std::cout << "Value of " << #x << " is: " << x << std::endl);

Its used like this:

int x = 1;
int y = 2;
MYLOG(x+y);

with the result being this:

Value of x+y is: 3

I have yet to duplicate this in any language that doesn't use the C preprocessor. Is it possible in any other language? I would like to be able to start using it elsewhere. Note: eval doesn't count. I want to see the expression in my code, not a string, so that I can still have syntax highlighting and autocomplete.

No, in both C and C++ the compiler removes symbol information. #x creates a string in the preprocessor, and the compiler does save strings.

Other languages with a stronger reflection capability may offer the ability to reflect on expressions. In particular, pure interpreted languages use just the string representation so they can trivially print that. However, that's where you object against eval . I don't understand why, some languages are 100% eval .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM