Last active
January 14, 2023 03:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.