Why don't C ++ compilers default initializing integers, floats and pointer variables?
Initialization is not always desirable:
-
For performance reasons; it takes time to initialize memory, which may not be needed. There are even algorithms that depend on a constant allocation of time to achieve the desired performance (initialization is linear time). D recognizes this, but has a different (probably better) approach; variables are initialized by default, but have special syntax to prevent initialization.
-
Sometimes there is no correct default. Static analysis or runtime debugging functions can help detect when a variable is used without initialization. Merely giving them some (wrong) default value can hide the error that will be caught by these.
source to share
There are several aspects to your question. First of all, the standard does not provide for such behavior. But where it does not violate the standard, it is possible. In fact, debug builds for example. in MSVC, do the exact opposite and initialize not with 0
, but with some magic value - another magic value is used to fill the "freed" memory. Again, this is specific to debug builds and can help spot certain classes of bugs, while it can hide other bugs or hide them where the codebase is.
But I think the performance issue is bigger here. If you were to initialize integers and float, why aren't all struct or array types both on the heap and on the stack? The problem with this, of course, is that if I write my program and allocate a buffer to read data into it, why would I waste time zeroing the buffer if I know I will be reading x bytes and the buffer is only x bytes length?
I agree that relying on this "random" behavior, as was the case with SSH in Debian, was wrong, but it shows that people rely on existing behavior and the consequences of changing this behavior will not always be obvious.
source to share
Not really. Apart from the reasons provided in other answers, I would like to point out that:
a) Global variables, static local variables are always initialized, if not explicitly, then implicitly zero.
b) For a custom class `class Test`, creating a new instance by `Test *ptr=new Test()` or `Test test;` gives an initialized object.
To summarize, things that go into the .data '.bss' sections of the ELF file are initialized either explicitly or implicitly (zero). Other variables in primitive types that are not in the mentioned scope have undefined content prior to explicit initialization (depending on your compiler). This is because the ELF file itself provides a way to initialize variables in a)
at a very low cost, while initializing variables on the stack, heap, etc. Can be a terrible job.
You might argue that it class Object
might be more costly to initialize. But first of all, omitting initialization for primitive types is how things work in C, and therefore C ++ conforms to it.
source to share