When the control flow off the end of a function without a return, why there is still a returned value?

  • A+
#include <iostream>  int func(int &a,int &b){     if (a>b){         return 1;     } }  int main(){     int a=4,b=12;     std::cout<<func(a,b)<<std::endl; } 

I think a run time error should occur because a is smaller than b, and the return statement is skipped. But it actually outputs the value of b no matter how I change the value of b. Could you please tell me why?


This is happening because a result of functions (if the return type is int) is transferred using rax register of CPU. return keyword places its argument in this register and returns to the caller function. But there is also an implicit return keyword at end of any function in C/C++ (if there is no explicit return placed by a programmer). And this is why this function returns control flow to the caller function.

But contents of rax register should be treated in this case as random because the compiler can use it for any variable or even totally ignore it.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: