我想知道编译器是否有办法理解两个if语句不能同时为true,并添加“隐式else”.例如,在此代码示例中:
int main() {
char c;
scanf_s("%c", &c, 1);
if (c == '1') {
printf("received 1\n");
}
if (c == '2') {
printf("received 2\n");
}
return 0;
}
c不能是’1’和’2′,但是在Visual Studio中进行编译和反汇编后,我注意到它会检查第二个是否,无论如何.
最佳答案
I want to know if there is way for the compiler to understand that two if statements can’t be true at the same time, and to add an “implicit else”.
是的:英特尔C编译器icc 17可以用Matt Godbolt’s Compiler Explorer验证,但clang和gcc似乎都没有执行此优化.