Hacker News new | ask | show | jobs
by perokreco 5516 days ago
It is not that the result of operation is undefined, the operation of INT_MAX+1 itself is undefined(actually the entire program becomes undefined when you do it), so the compiler can do whatever it pleases. According to the C standard, INT_MAX+1 might as well lead to formatting of your hard drive. So, it is safe to assume that x!=INT_MAX and that x+1>x for all x, because if x=INT_MAX your program is undefined, so compiler can do whatever it wants, including setting it to true or outputting an error or formatting the hard drive.
1 comments

This kind of logic is the exact cause to the optimization problem described. We all know that in practice MAX_INT+1 is negative, and that many "non-standard" programs depends on it, but still, the optimizer is sticking to the C standard that no one follows just because it gives it a nice optimization chance. Bad..
No, people like you are the cause of the problem described. The whole point of the article is that "we all know that in practice MAX_INT+1 is negative" is wrong.

Apologies for the confrontational tone, but someone making that kind of mistake out of ignorance is understandable. Insisting on wrong thinking after having it explained in detail why it's wrong, isn't.

If you can't live with the fundamental design principles behind C/C++ then the correct approach is to not use them. Don't ask the compiler writers to go against those principles.

"Bad"? You use C because you want speed above all else. If you don't know the language and need hand-holding, don't use C. Compilers are going to optimize C -- that's why it usually runs so fast.
This is bad because the optimizer ignores the imperfect reality about the big crowd of non standard programs. It actually punishes non standard programs (and probably the majority of programs out there are not 100% standard). So it is a bad and patronizing optimization
How many programs are there that depend on SIGNED overflow wrapping around to negative? I can't think of very many - the only places I've seen potential signed overflow that wasn't a bug was when people were checking for overflow.

In those cases, just use unsigned math to do the checks.

So how about a hypothetical architecture that instead of using two's complement, stores negative numbers with a negative flag bit for some reason? Would MAX_INT+1 still be negative on such an architecture?

"We all know that in practice" type assumptions are exactly what make code difficult to port and/or maintain and developers should really stay away from them. Or at least, if you really want to make such assumptions (for example, for performance reasons), make sure that that (1) you know exactly what you're doing and (b) test for their validity at compile time or runtime and provide fallback code that always does the "right" thing.