Hacker News new | ask | show | jobs
by SoftwareMaven 4005 days ago
That's is not remove code due to undefined behavior, so is an apples/oranges comparison. If we keep your function, but the call looks like this:

    int value1, value2;
    value1 = compute_value_1()
    ComputeStuff(value2)  # oops, fat-fingered the '2'
Do you really think the author meant to not have ComputeStuff run? Since value2 isn't initialized, it could be optimized out.

Yes, in this case, you would get a warning, but it is illustrative of the kinds of things can cause optimizers to do very unexpected things to your code. And it is surprisingly easy to find the UB conditions.

It's worth reading through this three-part post called What Every C Programmer Should Know About Undefined Behavior[1] from the LLVM folks to see how UB can screw with you, including removing NULL checks, eliminating overflow checks, and making debugging incredibly difficult to follow. It also explains why they can't just generate errors while optimizing.

1. http://blog.llvm.org/2011/05/what-every-c-programmer-should-...

1 comments

I don't think it is apples and oranges. Here's my next example:

    int ComputeStuff(int *value) {
        if(value == NULL) {
            long and complex computation for a NULL value
            return result
        } else {
            long and complex computation using the data pointed to by value
            return result
        }
    }
Then I call it from somewhere else like so:

    // NOTE: value must be non-NULL
    void DoStuff(int *value) {
        int pointedTo = *value;
        // do some work with pointedTo
        int computedResult = ComputeStuff(value);
        // do some more work with whatever
    }
Now, are you saying the compiler should not take advantage of the fact that it knows value is non-NULL at this particular call site and eliminate half of the code in this situation?