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

There was an article recently about a behavior which in a recent version of C++ was made from defined behavior into undefined behavior, because making it undefined allowed for better compiler optimizations.

I always thought that undefined behaviors were historical accidents. But apparently sometime people just say "hey, lets add a few more undefined behaviors"

This is the insanity of C++



I am happy to be proven wrong but I feel that they’d never change defined behavior to undefined. Unspecified to undefined sounds more likely.

There’s this article [1] about compilers exploiting undefined behavior but ... it’s already undefined behavior.

[1] https://devblogs.microsoft.com/oldnewthing/20140627-00/?p=63...


This sounds wrong. You're probably thinking of undefined behavior that happened to behave the same across all available C++ compilers, so people began to rely on it. But since it was technically undefined behavior, optimizers were free to take advantage of it, and when they started to it smashed any code that relied on that undefined behavior behaving in a consistent way.


While technically correct, (which is the best kind of correct), the sad reality is that de-facto standards matter. Languages that understand this tend to be safer than languages that do not.


Can you please find a reference? That sounds interesting.


Not exactly what you asked for, but C11 added this bit that was not there in C99:

An iteration statement whose controlling expression is not a constant expression, that performs no input/output operations, does not access volatile objects, and performs no synchronization or atomic operations in its body, controlling expression, or (in the case of a for statement) its expression, may be assumed by the implementation to terminate.

And C++11 added this bit that wasn't there in C++03:

A loop that, outside of the for-init-statement in the case of a for statement, - makes no calls to library I/O functions, and - does not access or modify volatile objects, and - performs no synchronization operations (1.10) or atomic operations (Clause 29) may be assumed by the implementation to terminate.

[Note: This is intended to allow compiler transformations, such as removal of empty loops, even when termination cannot be proven. -- end note]


In the article the compiler noticed that because of the loop iterator reading the array a[i+1] ... under the assumption the program never indexed beyond the end of the array ... The compiler assumed the loop variable was always less than the limit and therefore changed the loop into an infinite loop. This is the insanity of some of the newer compilers which assume your program never performs an undefined behavior. They compile your mildly buggy slightly undefined code into shit*.




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

Search: