Returning local structure?

I have a code:

struct point makepoint(int x, int y)
{
     struct point temp;
     temp.x = x;
     temp.y = y;
     return temp;
}

We have a problem here, because we are returning a local structure, isn’t it destroyed after the completion of the makepoint function ? This code is from the book.

C Programming Language (Second Edition) by Brian W. Kernigan • Dennis M. Ritchie

.

+4
source share
3 answers

In C, values ​​are passed, so there will be no problem with the way you do this.

When a return is made, the value of the variable is returned temp. Even if the variable is destroyed after the function returns, there will be no problems.

+2
source

temp is a variable with automatic storage, so yes, it will no longer be available when the function returns.

temp, temp. , , .

+2

Unlike arrays, structs are copied when passed as a parameter or when returned, as is the primitive type ( int).

0
source

All Articles