Implicit else compiler optimization

I want to know if there is a way for the compiler to understand that two statements ifcannot be true at the same time and add an “implicit other”. For example, in this code example:

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;
}

cIt can not be '1'and '2', but after compiling in Visual Studio and disassembly, I noticed that he would check the second if, no matter what.

+4
source share
4 answers

I want to know if there is a way for the compiler to understand that two if statements cannot be true at the same time and add an “implicit other”.

, : Intel C icc 17, Matt Engineer Compiler Explorer, clang gcc, , .

+1

LLVM/CLANG, .

mem2reg opt, c , ( ).

, , , DCE.

LLVM, "elseif".

, gcc/msvc.

0

, ? , , , , , , , , , , .

0

scanf_s() c, . , -, ( ) - , , printf("received 1\n").

In other words, the compiler cannot perform this optimization if it does not know what functions scanf_s()and do printf().

0
source

Source: https://habr.com/ru/post/1671139/


All Articles