Hacker News new | past | comments | ask | show | jobs | submit login

I'll bite. It seems like a number of these would complain about perfectly benign code.

Here's an example I can think of:

    b = (a == 0) ? 42 : 42;
A lot of readers are probably thinking this line is absurd and why on earth would a compiler not yell at you and call you a bad human being for writing this?

But let's be creative ... What if each of those 42s are expansions of different macros that vary based on an ifdef? You could have one platform or configuration where it expands to ? 43 : 42, and another where it expands to ? 42 : 42. Since the preprocessor does those expansions early, your compiler doesn't know the difference at the time of generating the warning. I just confirmed this in a small program, replacing the first 42 with FOO, the 2nd with BAR, and #defining them both to 42:

    warn.c:9:23: warning: this condition has identical branches [-Wduplicated-branches]
        b = (a == 0) ? FOO : BAR;
Overall I would say items in this list are not equally bad. Some of them unambiguously you want to flag. Others are things that people might do intentionally.



This is another reason why macros should not be treated or even viewed as source transformation passes. There is information loss involved in that. There's no reason the compiler shouldn't be able to only warn in the absence of a macro expansion.


The compiler passes of both GCC and Clang are aware of macro expansions since they are able to tell you about errors which occur after a macro expansion, i.e. the error messages similar to "... in expansion of macro X ...".


Yeah I'm aware. I'm more referring to the comments here, where people use "this is generated by a macro" as a justification even though that only makes sense if you think of preprocessed code as a separate stage from the actual code, which I'm arguing you shouldn't. That said though, I'm surprised they don't treat it that way for other cases like these?


Sometimes you might care about differing macros that expand to the same thing in a case like this example. The key point is the compiler can't read your mind to know when those cases are.


In this case, it'd probably be best to have another ifdef that makes

    b = 42
If the two macros are expanded to the same value. The compiler should optimize it out, anyway, but I'm a pythonista and I believe explicit is better than implicit, so, if you can write the optimal code explicitly, you probably should (unless it becomes unreadable if you do).




Consider applying for YC's W25 batch! Applications are open till Nov 12.

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

Search: