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’
Another approach to default values. Make an initialization function with the same type as the struct. This approach is very useful when splitting large code into separate files.
An initialization function to a struct is a good way to grant it default values:
Or even shorter:
Create a default struct as the other answers have mentioned:
However, the above code will not work in a header file - you will get error:
multiple definition of 'MyStruct_default'
. To solve this problem, useextern
instead in the header file:And in the
c
file:Hope this helps anyone having trouble with the header file.
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:
And then always initialize your new instances as:
Another approach, if the struct allows it, is to use a #define with the default values inside:
Use:
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,
in C++ its possible to give direct value in definition of structure shown as below