Skip to content

Instantly share code, notes, and snippets.

@yyasuda
Last active January 14, 2023 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

My Mac shows the result as follows;

$ ./a.out
sub 19 0 123502688
main 123502688 1 2
$ ./a.out
sub 19 0 129785952
main 129785952 1 2
$ ./a.out
sub 19 0 56098912
main 56098912 1 2
$

@yyasuda
Copy link
Author

yyasuda commented Jan 14, 2023

Original source is here;
https://gist.github.com/yyasuda/bb6c0ad6ffcbf6a526d775c360398a98

It shows the (right) answer "3".

@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