Some people are not aware that it's possible to pass and return structs by value in C. My question is about the compiler making unnecessary copies when returning structs in C. Do C compilers such as GCC use Return value optimization(RVO) optimization or is this a C++ only concept? Everything I have read about RVO and copy elision is in regards to C++.
Let's consider an example. I'm currently implementing a double-double data type in C (or rather float-float to start with because I find it easy to unit test). Consider the following code.
typedef struct {
float hi;
float lo;
} doublefloat;
doublefloat quick_two_sum(float a, float b) {
float s = a + b;
float e = b - (s - a);
return (doublefloat){s, e};
}
Will the compiler make a temporary copy of the doublefloat
value I return or can the temporary copy be elided?
What about named return value optimization (NRVO) in C? I have another function
doublefloat df64_add(doublefloat a, doublefloat b) {
doublefloat s, t;
s = two_sum(a.hi, b.hi);
t = two_sum(a.lo, b.lo);
s.lo += t.hi;
s = quick_two_sum(s.hi, s.lo);
s.lo += t.lo;
s = quick_two_sum(s.hi, s.lo);
return s;
}
In this case i'm returning a named struct. Can the temporary copy in this case be elided?
It should be stated that this is a general question for C and that the code examples I have used here are only examples (when I optimize this I will be using SIMD with intrinsics anyway). I'm aware that I could look at the assembly output to see what the compiler does but I think this is an interesting question nevertheless.
C
tag as it seems erreanous to me. – ChummyCan the temporary copy in this case be elided?
I wouldn't be the least bit surprised if this optimization existed in commercial C compilers dating back 20 or so years ago. It just got fancied up by C++ because, as the answer mentioned, C++ has side-effects to consider. – Jourdan