cfunctionreturncall-by-value

which part of the memory does the result of the expression of the return statements gets stored in?


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?


Solution

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

    Depends on the specific calling convention for the target architecture, usually in a register (such eax on x86).

    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;
    }
    

    In the first case you are returning the result of the expression A, which is simply the integer value 20; IOW, the value 20 is 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 variable A in func. The problem with this is that once func exits A ceases 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.