Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default value for struct member in C

Tags:

c

struct

Is it possible to set default values for some struct member? I tried the following but, it'd cause syntax error:

typedef struct {   int flag = 3; } MyStruct; 

Errors:

$ gcc -o testIt test.c  test.c:7: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token test.c: In function ‘main’: test.c:17: error: ‘struct <anonymous>’ has no member named ‘flag’ 
like image 439
user1508893 Avatar asked Dec 05 '12 05:12

user1508893


People also ask

Are struct members initialized 0?

If a structure variable has static storage, its members are implicitly initialized to zero of the appropriate type. If a structure variable has automatic storage, its members have no default initialization.

How do you initialize a struct value?

Another method to initialize struct members is to declare a variable and then assign each member with its corresponding value separately. Note that char arrays can't be assigned with string, so they need to be copied explicitly with additional functions like memcpy or memmove (see manual).

Are struct members default initialized C++?

When we define a struct (or class) type, we can provide a default initialization value for each member as part of the type definition. This process is called non-static member initialization, and the initialization value is called a default member initializer.

Does struct have default constructor?

The simple answer is yes. It has a default constructor. Note: struct and class are identical (apart from the default state of the accesses specifiers).


1 Answers

Structure is a data type. You don't give values to a data type. You give values to instances/objects of data types.
So no this is not possible in C.

Instead you can write a function which does the initialization for structure instance.

Alternatively, You could do:

struct MyStruct_s  {     int id; } MyStruct_default = {3};  typedef struct MyStruct_s MyStruct; 

And then always initialize your new instances as:

MyStruct mInstance = MyStruct_default; 
like image 63
Alok Save Avatar answered Oct 09 '22 09:10

Alok Save