Simultaneous execution of both if and else blocks

后端 未结 13 2309
难免孤独
难免孤独 2020-12-10 17:45

In C or C++

if ( x )
    statement1;
else
    statement2;

For what value of x will both statements be executed?

I know

13条回答
  •  粉色の甜心
    2020-12-10 18:06

    First off, this isn't a stupid question :)

    To understand why you can't accomplish this with any special trickery, we need to step down to the assembly that gets generated by an if-statement (particularly, the assembly for an Intel processor with gcc 4.2.1 -- different architectures will result in different assembly).

    Take this simple C program:

    #include 
    
    int main()
    {
        int i;
        scanf("%d", &i);
        if (i == 8)
        {
            return 100;
        }
        else
        {
            return 3;
        }
    }
    

    If the user enters a non-zero integer, we return 100; otherwise we return 3. The actual condition doesn't really matter here, because we're only interested in the assembly generated for main:

            ; ...
            call    _scanf
            movl    -4(%rbp), %eax
            cmpl    $8, %eax
            jne     L2
            movl    $100, -20(%rbp)
            jmp     L4
    L2:
            movl    $3, -20(%rbp)
    L4:
            movl    -20(%rbp), %eax
            leave
            ret
    

    I'm going to assume you have no knowledge of assembly -- but don't worry, this example isn't terribly hard to keep up with. What's happening here is that we call scanf, and we compare the result of it (i) with 8.

    Next, there's a Jump if Not Equal instruction to the label L2. This means that if i is equal to 8, the following instructions executed are:

    • Move 3 into rbp
    • Move rbp into eax
    • Leave (thereby returning the value 3 from the program).

    However, if i is not equal to 8, then when we hit the jne instruction, we don't jump. Instead, we:

    • Move 100 into rbp
    • Jump unconditionally to the label L4
    • Move rbp into eax and end up returning 100 from the program.

    With the assembly generated here, there are really only two possible branches. You can't arbitrarily reorder the code.

    So would it be possible to execute both branches (when they aren't both return statements)? Yes, on the condition that your compiler is incapable of correctly producing branching code. But that would never happen on a production-level compiler.

提交回复
热议问题