Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

#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?

like image 578
LearningCpp Avatar asked Nov 29 '22 21:11

LearningCpp


2 Answers

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.

like image 192
eerorika Avatar answered Dec 01 '22 10:12

eerorika


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.

like image 33
shitpoet Avatar answered Dec 01 '22 11:12

shitpoet