#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?
it should detect a run time error
That is not the case. The behaviour is undefined.
It seems to be related the value of b, why is that happening?
Because the behaviour is undefined.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With