Home > front end >  Is it ok to return address of rvalue in inline functions?
Is it ok to return address of rvalue in inline functions?

Time:06-22

I know that inline functions get copied into the code each time they are referenced. From my current understanding, I think it would be ok to return the address of an rvalue from an inline function since the function is inside the rest of the code and therefore the rvalue belongs to the scope of the caller function. Is this true?

example:

inline int* addressOfNum(int num){
    return #
} 

int main(){
    int* mynum = addressOfNum(9);
    
    // is the answer "11" or "segmentation fault"?
    int eleven = *mynum   2;
}

CodePudding user response:

Whether a function is inline has no effect on whether it's ok to return an address of any value.

It can be sometimes ok to return address of an rvalue if it is an xvalue that refers to an object outside the function.

num is not an rvalue expression. Returning an address of a function parameter of object type is never useful. The example function returns an invalid pointer and the behaviour of the program is undefined.

CodePudding user response:

inline does not mean that a function will be inlined. This was always only a hint to the compiler.

Since C 17 this has been codified in the standard and inline now basically just means "multiple definitions are permitted".

Read the details on https://en.cppreference.com/w/cpp/language/inline

And even if the function is inlined it still has to behave as-if it wasn't inlined. Returning the address of an argument is UB, inlined or not.

  • Related