error: unused variable 'part2' [-Werror,-Wunused-variable]
The error occurs only for part2 even though it's been initialized as well, just in a different manner. Is it just a compiler issue ?
int main(void)
{
struct complex
{
int a;
int b;
};
struct complex part1;
part1.a = 2;
part1.b = 3;
struct complex part2 = {4, 5};
struct complex part3 = {part3.a = 7, part3.b = 8};
}
As has been mentioned in the comments above, part1
is considered "used" because you assign values to its fields (a
and b
) explicitly in the following lines:
part1.a = 2;
part1.b = 3;
part2
is never used, only initialized in the line:
struct complex part2 = {4, 5};
part3
is more interesting, and I'm surprised your compiler is not throwing an error. By doing the following:
struct complex part3 = {part3.a = 7, part3.b = 8};
you are first assigning part3.a = 7
and part3.b = 8
, then the results of those assignments are being used to initialize the structure (part3.a = 7
evaluates to 7
, part3.b = 8
evaluates to 8
). It essentially becomes the following set of statements:
part3.a = 7;
part3.b = 8;
struct complex part3 = {7, 8};
I would expect your compiler to throw an error because you are attempting to assign values to the fields of part3
before you have instantiated it. This is undefined behavior.