Hacker News new | ask | show | jobs
by mikeash 4892 days ago
You certainly could define some basic things to make the language safer. For example, make variables always be initialized to zero if not explicitly initialized, and force accessing beyond the bounds of an array to be a fault rather than undefined behavior.
2 comments

You could, but that comes at a cost. That's why libraries like the STL in C++ provide std::vector::operator[] and std::vector::at() - so the user can freely choose whether to pay the extra cost for the bounds check, or not. That's why C provides both malloc() and calloc() - so the user can freely choose whether memory is zero-initialized, or not.

One of the major design decisions for C/C++ is that you don't pay for what you don't use. This is what makes them so flexible and performant across a wide range of systems and applications, but also leaves these safety choices up to the user. Some languages make that tradeoff, but it's not always the right decision.

On the other hand there are languages where correctness comes before speed, and they still provide you the mechanisms to get speed if you really want.

For example, in the Pascal family of languages, you can always disable bounds checking or do pointer arithmetic if you really want to, but that should only be done if there is really the need to do so.

A problem with many C and C++ developers is that they suffer from premature optimization, thinking that we are still targeting PDP-11 like environments.

Initializing variables to zero doesn't buy you much in terms of safety, IMHO. The value 0 isn't necessarily any more valid than an arbitrary value. Better is Java/ML/Haskell's rule whereby variables must be explicitly initialized before use. This can be implemented with a simple compiler pass.
At least the value 0 is always the same and doesn't subtly change from one invocation to the next or from one machine to the next. It certainly helps in making programs more robust, even if there is still a problem at code level.
Java? Everything (except for built-in types) is nullable in Java...
pcwalton's point is that you must be explicit about initializing variables:

  int foo = 1;
  int bar;
  System.out.println(foo + bar);  // compile error: variable bar might not have been initialized