r/cprogramming – Compiler optimization on Undefined Conduct
Hello all,
I’m making an attempt to grasp this article on undefined conduct however having a tough time greedy, how the compiler optimized the beneath perform;
int desk[4];
bool exists_in_table(int v)
{
for (int i = 0; i <= 4; i++)
{
if (desk[i] == v) return true;
}
return false;
}
to
bool exists_in_table(int v)
{
return true;
}
Compiler Explorer, confirms the creator’s evaluation.
When i is 4, the code performs undefined conduct. Since undefined conduct lets me do something I need, I can completely ignore that case and proceed on the belief that i isn’t 4.
Okay, I get this half. Compiler assumes i == 4 code path won’t ever occur
Subsequently, all authorized code paths return true.
Undecided about this conclusion. Why did the compiler ignore the if-condtion in addition to assume <v> might be in <desk> ?
I hoped that it will likely be optimized to the beneath as a substitute;
bool exists_in_table(int v)
{
return false; // Reasoning : for-block invokes undefined conduct, so let's ignore it.
}
Thanks prematurely for the assistance.