Today I was teaching a couple of friends how to use C struct
s. One of them asked if you could return a struct
from a function, to which I replied: "No! You'd return pointers to dynamically malloc
ed struct
s instead."
Coming from someone who primarily does C++, I was expecting not be able to return struct
s by values. In C++ you can overload the operator =
for your objects and makes complete sense to have a function to return your object by value. In C, however, you do not have that option and so it got me thinking what the compiler is actually doing. Consider the following:
struct MyObj{
double x, y;
};
struct MyObj foo(){
struct MyObj a;
a.x = 10;
a.y = 10;
return a;
}
int main () {
struct MyObj a;
a = foo(); // This DOES work
struct b = a; // This does not work
return 0;
}
I understand why struct b = a;
should not work -- you cannot overload operator =
for your data type. How is it that a = foo();
compiles fine? Does it mean something other than struct b = a;
? Maybe the question to ask is: What exactly does the return
statement in conjunction to =
sign do?
struct b = a;
is a syntax error. What if you trystruct MyObj b = a;
? – Nagaristruct MyObj b = a;
does seem to work :) – Spragensstruct
is a properly first-class type, and can be assigned, passed, and returned with impunity. You don't have to define your ownoperator=
(as indeed you could in C++), because any struct is by definition POD, and a simplememcpy
-like assignment, which the compiler is perfectly willing to perform, is sufficient. See also What does impossibility to return arrays actually mean in C? – Coenocyte