The problem
I’m trying to understand how C++ compilers handle undefined variables, and I’ve written the following code :
int test() {
bool b; //undefined
if(b){return 1;}
else {return 2;}
return 0;
}
Clang
When I compile with x86_64 clang 18.1.0 with flags -O3 -std=c++23
I get the following assembly
test(): # @test()
Which means : this function does nothing (it evens doesn’t return).
Gcc
When the same code is compiled with x86_64 gcc 14.1 with flags -O3 -std=c++23
I get the following assemblby :
test():
mov eax, 2
ret
which means : return 2.
My question
I’m confused as I thought that when a variable is undefined, the compiler is allowed to choose a path (based on whatever rule it wants) so I expected either 1 or 2 in the return value as gcc does, but I didn’t explected an invalid function as clang does.
Can you please explain me what’s the standard rule the compiler should follow when they test an undefined variable. And who’s wrong (my expectations, clang, gcc) ?.
I tried to get illumination by drinking a coffee. I’m now caffeinated, not illuminated.
Jacques Lavalée is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.