I have a general question about how MSVC generates machine code regarding to else
statement.
A simple exmaple here:
1 bool is_zero(int num) {
2 if (num)
3 return false;
4 else
5 return true;
6 }
and its disassembly code looks like
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.20.27508.1
; Function compile flags: /Odtp
num$ = 8
bool is_zero(int) PROC ; is_zero
; File C:\Users\ContainerAdministrator\AppData\Local\Temp\compiler-explorer-compiler11943-18164-1cmj5fb.ujww\example.cpp
; Line 1
mov DWORD PTR [rsp+8], ecx
; Line 2
cmp DWORD PTR num$[rsp], 0
je SHORT $LN2@is_zero
; Line 3
xor al, al
jmp SHORT $LN1@is_zero
; Line 4
jmp SHORT $LN3@is_zero
$LN2@is_zero:
; Line 5
mov al, 1
$LN3@is_zero:
$LN1@is_zero:
; Line 6
ret 0
bool is_zero(int) ENDP ; is_zero
Question is:
will the line jmp SHORT $LN3@is_zero
(corresponding to the 4th line else
keyword) get executed?
is there any good reason MSVC generates such code?
It's unoptimized code. That line 4 jmp
corresponds to the jump from the if
body past the else
body. In this case it is never executed. Enable optimizations and it will go away.