I a C source code, I would like to ensure that all elements of my structure are well initilized. It would be easy with the warning Wmissing-field-initializers. But I also would like to be able to initialize my elements using designated initilizer.
for example:
struct s {
int a;
int b;
};
struct s s1 = { .a = 1, .b = 2 };
struct s s2 = { .a = 1 };
struct s s3 = { 1, 2 };
struct s s4 = { 1 };
Let's try to compile this:
$ gcc -Wmissing-field-initializers -c struct_init.c
struct_init.c:9:8: warning: missing initializer
struct_init.c:9:8: warning: (near initialization for ‘s4.b’)
I would like the compilation fails for s2 initilization too. I do prefer designated initiazation, as it facilitates source code reading.
When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.
// In C++ We can Initialize the Variables with Declaration in Structure. Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.
Initializing structure members struct car { char name[100]; float price; }; //car1 name as "xyz" //price as 987432.50 struct car car1 ={"xyz", 987432.50};
You can't. NULL is a pointer whose value is set to zero, but your mark and space properties are not pointer values. In your code as you have it, they will both be value types, allocated as part of your Pair struct. Change the variables to Segment * instead of Segment , and you will be able to set them to NULL.
When you use designation initializers, the missing members are initialized to 0
. This is the case even if the object has automatic storage duration. To my knowledge there is no gcc
option that can warn about the members that are not explicitly initialized when you use designation initializers.
You could use -Werror to turn warnings into errors or alternatively -Werror=missing-field-initializers to only turn the field initializer warning into an error.
More info here: GCC Warning Options
Edit: I just ran a test using splint with no additional options which gave the following output:
main.c:13:17: Initializer block for s2 has 1 field, but struct s has 2 fields:
<error>
Initializer does not set every field in the structure. (Use -fullinitblock to
inhibit warning)
main.c:15:17: Initializer block for s4 has 1 field, but struct s has 2 fields:
1
It may not be exactly what you are after since you need to run this manually against your source but it will warn about missing designated initializers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With