Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not assign interchangeably with two structs that have identical contents?

Tags:

c

struct

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 structs 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?

like image 920
Mithrax Avatar asked Apr 13 '09 16:04

Mithrax


People also ask

Can you set two structs equal to each other?

Yes, you can assign one instance of a struct to another using a simple assignment statement.

Why can't we create an object of structure within the same structure?

you can not put a whole struct inside of itself because it would be infinitely recursive.

Can you assign a struct to another?

Assigning one struct to anotherIf two variables are of the same struct type, then they can be directly assigned one to the other.

Can you equate structures in C?

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.


2 Answers

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;
like image 66
John Millikin Avatar answered Oct 27 '22 01:10

John Millikin


Making identically structured types the same is called "duck typing". This is done in some languages, but not in C.

like image 38
Don Reba Avatar answered Oct 27 '22 00:10

Don Reba