I'm trying to learn C and I've come across something weird:
struct
{
int i;
double j;
} x, y;
struct
{
int i;
double j;
} z;
Here, you can see I created two struct
s that are identical in their elements.
Why is it that when I try to assign x = z
it will generate a compile error but x = y
does not? They have the same contents, so why can't I assign them back and forth with each other, regardless?
Is there any way I can make this so I can assign x = z
? Or do they simply have to be the same struct
.
Can any C gurus point me in the right direction?
Yes, you can assign one instance of a struct to another using a simple assignment statement.
you can not put a whole struct inside of itself because it would be infinitely recursive.
Assigning one struct to anotherIf two variables are of the same struct type, then they can be directly assigned one to the other.
In C, the only operation that can be applied to struct variables is assignment. Any other operation (e.g. equality check) is not allowed on struct variables.
They have the same content, but not the same type. If they are intended to be of the same type, simply typedef x z;
. If they aren't the same thing, but just happen to contain the same fields, it's better to create a separate function that will assign the fields properly.
My usual style for declaring structs in C includes the typedef, so I forgot to mention it (sorry!). Here's the syntax:
typedef struct
{
int foo;
double bar;
} x;
/* Further down, if needed */
typedef x z;
Making identically structured types the same is called "duck typing". This is done in some languages, but not in C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With