我正在从事的项目是用 C 编写的,并使用预处理器宏来处理错误。
宏看起来像这样:
#define logevent(level, msg) \
do {
int _level = level; \
somefunction(_level, msg); \
someotherfunction(_level, msg); \
if (_level >= ERROR) \
__assume(0); \
} while(0)
假设如果级别 >= ERROR,某个其他函数会退出(1),而当我们调用 logevent(ERROR, "something") 时,我们永远不会达到 if 条件;其中 ERROR 是定义的常量。 问题是 MSVC 似乎无法优化 if 条件,因为 if 条件基于 _level 变量而不是 level 常量。需要 _level 变量来停止对级别表达式的多次求值。
某些其他编译器似乎能够优化掉 if,但我想知道这是否是 MSVC 编译器的限制,或者我是否可以启用某些东西让编译器优化这些 if 条件?
最佳答案
MSVC 2013 将优化我们的表达式。以下输入
#define ERROR 1
void somefunction(int level, char const* msg) {
printf("FUNC1 %d: %s\n", level, msg);
}
void someotherfunction(int level, char const* msg) {
printf("FUNC2 %d: %s\n", level, msg);
if (level >= ERROR) {
exit(1);
}
}
#define logevent(level, msg) \
do { \
int _level = level; \
somefunction(_level, msg); \
someotherfunction(_level, msg); \
if (_level >= ERROR) \
__assume(0); \
} while (0)
int _tmain(int argc, _TCHAR* argv[])
{
logevent(ERROR, "HALLO");
printf("Hallo\n");
getchar();
return 0;
}
将编译为
00CB1000 push 0CB2120h
00CB1005 push 1
00CB1007 push 0CB2100h
00CB100C call dword ptr ds:[0CB2090h]
00CB1012 push 0CB2120h
00CB1017 push 1
00CB1019 push 0CB2110h
00CB101E call dword ptr ds:[0CB2090h]
00CB1024 add esp,18h
00CB1027 push 1
00CB1029 call dword ptr ds:[0CB208Ch]
关于c - MSVC 和优化常量表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21073520/