简体   繁体   English

无需C预处理程序即可记录表达式的文本及其结果

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

I use this macro in C/C++ very frequently: 我在C / C ++中经常使用此宏:

#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. 我还没有用任何不使用C预处理程序的语言来复制它。 Is it possible in any other language? 是否可以使用其他任何语言? I would like to be able to start using it elsewhere. 我希望能够在其他地方开始使用它。 Note: eval doesn't count. 注意:eval不计算在内。 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. 不,在C和C ++中,编译器都会删除符号信息。 #x creates a string in the preprocessor, and the compiler does save strings. #x在预处理器中创建一个字符串,并且编译器确实保存了字符串。

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 . 但是,这就是您反对eval的地方。 I don't understand why, some languages are 100% eval . 我不明白为什么,有些语言是100% eval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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