Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

structs in C with initial values [duplicate]

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 861
user1508893 Avatar asked Dec 05 '12 05:12

user1508893


People also ask

Can C structs have default values?

For variables of class types and other reference types, this default value is null . However, since structs are value types that cannot be null , the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null .

How do you give a struct a default value?

Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members. Another way of assigning default values to structs is by using tags.

Are structs default initialized?

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.

How are structs saved in memory C?

Structs are stored as a concatenation of the variables they are declared to contain. The variables are stored in the order they are declared. The address of the beginning of the struct is the address of the beginning of the first variable it contains.


2 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 181
Alok Save Avatar answered Oct 01 '22 02:10

Alok Save


you can not do it in this way

Use the following instead

typedef struct {    int id;    char* name; }employee;  employee emp = { .id = 0,  .name = "none" }; 

You can use macro to define and initialize your instances. this will make easiier to you each time you want to define new instance and initialize it.

typedef struct {    int id;    char* name; }employee;  #define INIT_EMPLOYEE(X) employee X = {.id = 0, .name ="none"} 

and in your code when you need to define new instance with employee type, you just call this macro like:

INIT_EMPLOYEE(emp); 
like image 22
MOHAMED Avatar answered Oct 01 '22 02:10

MOHAMED