Compiler optimizations with non initialized values
What the compiler does with the following code?
Obviously we see that we can return an uninitialized value.
#include <cstddef>
size_t f(int x){
size_t a;
if(x)
a = 42;
return a;
}
The compiler would generate
f(int):
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-20], edi
cmp DWORD PTR [rbp-20], 0
je .L2
mov QWORD PTR [rbp-8], 42
.L2:
mov rax, QWORD PTR [rbp-8]
pop rbp
ret
But what happens under -O1?
The following code is generated:
f(int):
mov eax, 42
ret
https://godbolt.org/z/eaPPM471G
Source: https://lwn.net/Articles/510338/