Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's perfectly safe.</p> <p>You're returning by value. What would lead to undefined behavior is if you were returning by reference.</p> <pre><code>//safe mystruct func(int c, int d){ mystruct retval; retval.a = c; retval.b = d; return retval; } //undefined behavior mystruct&amp; func(int c, int d){ mystruct retval; retval.a = c; retval.b = d; return retval; } </code></pre> <p>The behavior of your snippet is perfectly valid and defined. It doesn't vary by compiler. <strong>It's ok!</strong></p> <blockquote> <p>Personally I always either return a pointer to a malloc'ed struct</p> </blockquote> <p>You shouldn't. You should avoid dynamically allocated memory when possible.</p> <blockquote> <p>or just do a pass by reference to the function and modify the values there.</p> </blockquote> <p>This option is perfectly valid. It's a matter of choice. In general, you do this if you want to return something else from the function, while modifying the original struct.</p> <blockquote> <p>Because my understanding is that once the scope of the function is over, whatever stack was used to allocate the structure can be overwritten</p> </blockquote> <p>This is wrong. I meant, it's sort of correct, but you return a copy of the structure you create inside the function. <strong>Theoretically</strong>. In practice, <strong>RVO</strong> can and probably will occur. Read up on return value optimization. This means that although <code>retval</code> appears to go out of scope when the function ends, it might actually be built in the calling context, to prevent the extra copy. This is an optimization the compiler is free to implement.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload