- Thread Author
- #1
I was teaching a few of pals how to use C structs today. One of them inquired whether it was possible to return a struct from a function, to which I replied: "No! Instead, you would return pointers to dynamically mallocated structs."
Consider the following:
Coming from someone who typically works in C++, I was anticipating to be unable to return structs by values. With C++, you may overload the operator = for your objects, and it makes perfect sense to have a function that returns your object by value. Nevertheless, in C, you do not have that option, which made me wonder what the compiler is doing.
As stated in the documentation, my issue is: Since the two definitions of foo in the first instance are regarded the same, why isn't the same for foo ptr in the second case? In other words, why is const disregarded in the first example but not in the second?
Any would be appreciated
Consider the following:
Code:
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;
}
Coming from someone who typically works in C++, I was anticipating to be unable to return structs by values. With C++, you may overload the operator = for your objects, and it makes perfect sense to have a function that returns your object by value. Nevertheless, in C, you do not have that option, which made me wonder what the compiler is doing.
As stated in the documentation, my issue is: Since the two definitions of foo in the first instance are regarded the same, why isn't the same for foo ptr in the second case? In other words, why is const disregarded in the first example but not in the second?
Any would be appreciated