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
Even more so, to add on the existing answers, you may use a macro that hides a struct initializer:
#define DEFAULT_EMPLOYEE { 0, "none" }
Then in your code:
employee john = DEFAULT_EMPLOYEE;
You can use some function to initialize struct as follows,
typedef struct
{
int flag;
} MyStruct;
MyStruct GetMyStruct(int value)
{
MyStruct My = {0};
My.flag = value;
return My;
}
void main (void)
{
MyStruct temp;
temp = GetMyStruct(3);
printf("%d\n", temp.flag);
}
EDIT:
typedef struct
{
int flag;
} MyStruct;
MyStruct MyData[20];
MyStruct GetMyStruct(int value)
{
MyStruct My = {0};
My.flag = value;
return My;
}
void main (void)
{
int i;
for (i = 0; i < 20; i ++)
MyData[i] = GetMyStruct(3);
for (i = 0; i < 20; i ++)
printf("%d\n", MyData[i].flag);
}
Another approach, if the struct allows it, is to use a #define with the default values inside:
#define MYSTRUCT_INIT { 0, 0, true }
typedef struct
{
int id;
int flag;
bool foo;
} MyStruct;
Use:
MyStruct val = MYSTRUCT_INIT;
You can do:
struct employee_s {
int id;
char* name;
} employee_default = {0, "none"};
typedef struct employee_s employee;
And then you just have to remember to do the default initialization when you declare a new employee variable:
employee foo = employee_default;
Alternatively, you can just always build your employee struct via a factory function.
I agree with Als that you can not initialize at time of defining the structure in C. But you can initialize the structure at time of creating instance shown as below.
In C,
struct s {
int i;
int j;
};
struct s s_instance = { 10 ,20 };
in C++ its possible to give direct value in definition of structure shown as below
struct s {
int i;
s(): i(10)
{
}
};
You can use combination of C preprocessor functions with varargs, compound literals and designated initializers for maximum convenience:
typedef struct {
int id;
char* name;
} employee;
#define EMPLOYEE(...) ((employee) { .id = 0, .name = "none", ##__VA_ARGS__ })
employee john = EMPLOYEE(.name="John"); // no id initialization
employee jane = EMPLOYEE(.id=5); // no name initialization