Use of uninitialized variable is not reported when followed by initialization in loop
| Bugzilla Link | 49029 |
| Version | 11.0 |
| OS | Linux |
| CC | @DougGregor,@zygoloid |
Extended Description
The following code does not produce any warnings when compiled with 'clang++ weird.cpp -Wall'
int main() {
int x;
for (int i = 0; i < 10; i++) {
x += 1;
x = 0;
}
}
However, 'x' is uninitialized during the initial iteration through the loop. If the 'x = 0;' line is removed:
int main() {
int x;
for (int i = 0; i < 10; i++) {
x += 1;
}
}
then a warning is produced when compiled with 'clang++ weird.cpp -Wall'
weird.cpp:4:9: warning: variable 'x' is uninitialized when used here [-Wuninitialized]
x += 1;
^
weird.cpp:2:10: note: initialize the variable 'x' to silence this warning
int x;
^
= 0
1 warning generated.
The statement 'x = 0;' occurs after the uninitialized use of x, so it should not cause the warning to be suppressed.
The same behavior is still seen on post 16 trunk (c3b27c236d6a495acbe2ba95c43faf9a98e81a46)
with the warning appearing only when the x=0 line is removed
A slightly different warning does appear with -Weverything
When the code is
int main() {
int x;
for (int i = 0; i < 10; i++) {
x += 1;
}
return x;
}
and compiled with -Wall then the warning is warning: variable 'x' is uninitialized when used here [-Wuninitialized]
When you put back in the x=0 giving
int main() {
int x;
for (int i = 0; i < 10; i++) {
x += 1;
x = 0;
}
return x;
}
There is no warnings with -Wall but if you instead use -Weverything then you get the warning
warning: variable 'x' may be uninitialized when used here [-Wconditional-uninitialized]
https://godbolt.org/z/rfnMbY683