Re:A Guide to Undefined Behavior in C and C++
by toxicdevil on Thursday August 17, 2023 @08:37PM
(#37170178)
int table[4];
bool exists_in_table(int v)
{
for (int i = 0; i <= 4; i++) {
if (table[i] == v) return true;
}
return false;
}
i -> 0 goto return true or next iter
i -> 1 goto return true or next iter
i -> 2 goto return true or next iter
i -> 3 goto return true or next iteri -> 4 goto return true or exit loop and return false Since the branch in on undef behavior it is okay for the compiler to choose any branch destination or none at all (i.e. remove all further code). The compiler in this case likely chose to just remove the branch and any destinations. All that the prior code does is return true, since there is no next iter, so thats all what is left.
- a correct program does not access table[4] - therefore the loop must always exit early - the only way to exit early is to return true