Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why structs cannot be assigned directly?

Tags:

c

structure

Suppose I have a fully defined struct with tag MyStruct, and suppose that x, y, ..., z are allowed values for its fields. Why is

struct MyStruct q = {x,y,..,z}; 

allowed, but

struct MyStruct q; q = {x,y,...,z}; 

is not allowed? I find this very annoying. In the second case, where I have previously declared q, I need to assign a value to each field, one by one:

q.X = x; q.Y = y; ... q.Z = z; 

where X, Y, ..., Z are the fields of MyStruct. Is there a reason behind this?

like image 231
becko Avatar asked Aug 30 '12 03:08

becko


People also ask

Can structs be assigned?

Yes, you can assign one instance of a struct to another using a simple assignment statement. In the case of non-pointer or non pointer containing struct members, assignment means copy. In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.

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 copy one structure into another in C How?

If the structures are of compatible types, yes, you can, with something like: memcpy (dest_struct, source_struct, sizeof (*dest_struct)); The only thing you need to be aware of is that this is a shallow copy.

Can you put a struct within a struct?

C Nested StructureOne structure can be declared inside other structure as we declare structure members inside a structure. The structure variables can be a normal structure variable or a pointer variable to access the data.


1 Answers

What you are looking for is a compound literal. This was added to the language in C99.

Your first case:

struct MyStruct q = {x,y,..,z}; 

is a syntax specific to initialization. Your second case, in the pedantics of the language is not initialization, but assignment. The right hand side of the assignment has to be a struct of the correct type. Prior to C99 there was no syntax in the language to write a struct literal, which is what you are trying to do. {x,y,..,z} looked like a block with an expression inside. If one were inspired to try to think of it as a literal value, though the language didn't, one couldn't be sure of its type. (In your context, you could make a good guess.)

To allow this and resolve the type issue, C99 added syntax so you could write:

q = (struct MyStruct){x,y,...,z}; 
like image 121
Avi Berger Avatar answered Oct 08 '22 05:10

Avi Berger