typedef struct { int hour; int min; int sec; } counter_t;
And in the code, I'd like to initialize instances of this struct without explicitly initializing each member variable. That is, I'd like to do something like:
counter_t counter; counter = {10,30,47}; //doesn't work
for 10:30:47
rather than
counter.hour = 10; counter.min = 30; counter.sec = 47;
Don't recall syntax for this, and didn't immediately find a way to do this from Googling.
Thanks!
Yes, you can assign one instance of a struct to another using a simple assignment statement.
Struct initialization and default values All of a struct's member fields must be definitely assigned when it's created because struct types directly store their data. The default value of a struct has definitely assigned all fields to 0. All fields must be definitely assigned when a constructor is invoked.
Declaration. The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ };
When initializing an object of struct or union type, the initializer must be a non-empty, (until C23) brace-enclosed, comma-separated list of initializers for the members: = { expression , ... }
Initialization:
counter_t c = {10, 30, 47};
Assignment:
c = (counter_t){10, 30, 48};
The latter is called a "compound literal".
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