Throwing the end of a function without returning is undefined behavior, no matter what actually happens with your compiler. Please note that if you pass -O3 to GCC or use Clang , you will get different results.
As for why you really see the โrightโ answer, this is the x86 assembly that GCC 6.2 produces in -O0 :
push rbp mov rbp, rsp mov DWORD PTR [rbp-4], edi mov eax, DWORD PTR [rbp-4] cdq shr edx, 31 add eax, edx and eax, 1 sub eax, edx cmp eax, 1 nop pop rbp ret
Do not worry if you cannot read x86. It is important to note that eax used for the return value, and all intermediate calculations for the if use eax as the destination. Therefore, when the function exits, eax simply has the result of checking the branch.
Of course, all this is a purely academic discussion; the student code is wrong, and I would definitely give him zero marks, regardless of whether he passed all the tests through which you run him.
source share