There are many claims that any use of uninitialised variables invokes undefined behavior (UB).
Perusing the docs, I could not verify that claim, so I would like a convincing argument clarifying this for both C and C++.
I expect the same semantics for both, but am prepared to be surprised by subtle or not so subtle differences.
Some examples of using uninitialised variables to get started. Please add others as needed to explain any corner-cases they don't cover.
void test1() {
int x;
printf("%d", x);
}
void test2() {
int x;
for(int i = 0; i < CHAR_BIT * sizeof x)
x = x << 1;
printf("%d", x);
}
void test3() {
unsigned x;
printf("%u", x); /* was format "%d" */
}
void test4() {
unsigned x;
for(int i = 0; i < CHAR_BIT * sizeof x)
x = x << 1;
printf("%u", x); /* was format "%d" */
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…