Skip to content

Instantly share code, notes, and snippets.

@yyasuda
Last active January 14, 2023 03:19
Show Gist options
  • Save yyasuda/cf4d5ac4bc9fcb8bba255de0905a638f to your computer and use it in GitHub Desktop.
Save yyasuda/cf4d5ac4bc9fcb8bba255de0905a638f to your computer and use it in GitHub Desktop.
The initializer of a structure variable can include a reference to itself, but this case does not work. Order is matter.
/*
LLVM reports a warning as follows;
"variable 's' is uninitialized when used within its own initialization [-Wuninitialized]"
And it shows the answer randomly.
*/
#include <stdio.h>
typedef struct {
int a, b, c;
} S;
int sum(S s) {
printf("sub %d %d %d\n", s.a, s.b, s.c);
return s.b + s.c;
}
int main() {
S s = {sum(s), 1, 2};
printf("main %d %d %d\n", s.a, s.b, s.c);
return 0;
}
@yyasuda
Copy link
Author

yyasuda commented Jan 14, 2023

So the order matter. The initializer sets the value from left to right.
As an initializer of a structure variable, it is possible to place a function that refers to the variable itself. However, the function must be aware that only member variables before itself are initialized yet.

The assembled code of above "original" source is here;
https://gist.github.com/yyasuda/c5633cea0e9c9de303f15a3af4c5d324
You can understand what happened inside. How the initializer's order matter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment