Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a C struct inline?

Tags:

c++

c

struct

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!

like image 797
mindthief Avatar asked Jan 23 '11 23:01

mindthief


People also ask

Can you assign structs in C?

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

How do you initialize a structure in C#?

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.

How do you declare a struct type?

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. */ };

How do you initialize struct members?

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 , ... }


1 Answers

Initialization:

counter_t c = {10, 30, 47}; 

Assignment:

c = (counter_t){10, 30, 48}; 

The latter is called a "compound literal".

like image 81
Steve Jessop Avatar answered Sep 20 '22 08:09

Steve Jessop