Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The first example took me a few reads to get too.

Basically, since i=4 causes undefined behaviour, the compiler assumes that it can't possibly happen[1] and the only way that it can't happen is if one of the prior (i < 4) checks were true.

Therefore all legal code paths (ie all code paths that don't result in undefined behaviour) return true.

So it optimises it to simply return true. Because otherwise i=4 would have happened, but that's undefined, so impossible[1]

[1] but if it does happen, that's ok, because that would be undefined behaviour, which allows the compiler to do whatever it feels like anyway



[deleted]


Look at it as the compiler unrolling the loop to:

    if (table[0] == v) return true;
    if (table[1] == v) return true;
    if (table[2] == v) return true;
    if (table[3] == v) return true;
    undefined_behavior();
    return false;
Since the compiler is allowed to assume undefined behavior never happens, and you certainly can't expect control to pass through undefined behavior and then do something reasonable like execute the next statement, the compiler can just assume that control exits the function before it gets to the undefined behavior, and the only way to do that is to take one of these `return true;` statements. It can't tell you which table element supposedly contains v, but no one asked for that, so all these `return`s serve equally well.


Beautiful. That makes it very simple to understand. Cheers mate.


Okay, yea, that makes sense.

Awesome. Thanks.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: