the case is
int func(void){
int A = 10;
int B = 20;
return A+B
}
which is being called by the main function
int main(void){
int retVal = func();
return 0;
}
in the function func() two local variables will be stored onto the stack for the scope of func() but where does the result of A+B stored?
and over the call by reference, how reliable this method is?
what is the difference between following function bodies
int func(void){
int A = 20;
return A;
}
and
int* func(void){
int A = 20;
return &A;
}
why returning the values does not throw the error of the segmentation fault but returning the address do?
Depends on the specific calling convention for the target architecture, usually in a register (such
eaxon x86).In the first case you are returning the result of the expression
A, which is simply the integer value20; IOW, the value20is written to some register or other memory location, which is read by the calling function.In the second case you are returning the result of the expression
&A, which is the address of the variableAinfunc. The problem with this is that oncefuncexitsAceases to exist and that memory location becomes available for something else to use; the pointer value is no longer valid, and the behavior on dereferencing an invalid pointer is undefined.