Well, it good weirder. int types are 0s except char types which are 0xFF, 0xFFFF (-1). Except dchar (32bit uint) which is 0x0000FFFF. And all floating types are NaN. Why the inconsistency?
Is there a reason for this? If you are gonna initialize your locals why not 0 for all? It would be more expected, consistent and probably efficient.
I can confirm that. Found at least one bug due to NaN initialization, which would otherwise probably have silently corrupted my data without me noticing. When I found the reason source of the NaNs in my data it was a Neo-like Whoaaa feeling. Unfortunately, I cannot remember the details of the code, so only anecdotal evidence. ;)
The intention is to default-initialize values to things that are invalid. There's no obvious "invalid" value for a plain integer, so they get zero. But char gets 0xFF, because a char is defined to hold UTF-8 code units, and 0xFF is not a valid UTF-8 code unit. Similar logic extends to the larger character types, and to using NaN in a float.
The idea is that you should be initializing values explicitly before using them, and default-initializing to values which will rapidly fail makes it easier to debug use-before-initialization bugs than (for example) it is in C, where values are not initialized at all.
If you explicitly want to disable default initialization, you can use void as an initializer, as in:
Maybe setting to zero would faster. However, if you optimize on that level, then you can optimize by hand as well. Set it to zero explicitly or even let it uninitialized explicitly:
5 comments
[ 2.8 ms ] story [ 12.8 ms ] threadhttps://dlang.org/spec/type.html
Well, it good weirder. int types are 0s except char types which are 0xFF, 0xFFFF (-1). Except dchar (32bit uint) which is 0x0000FFFF. And all floating types are NaN. Why the inconsistency?
Is there a reason for this? If you are gonna initialize your locals why not 0 for all? It would be more expected, consistent and probably efficient.
Integer have no NaNs, so they are initialized with 0s since no other value really fits.
I don't know for chars but I guess there are good reasons as well.
The idea is that you should be initializing values explicitly before using them, and default-initializing to values which will rapidly fail makes it easier to debug use-before-initialization bugs than (for example) it is in C, where values are not initialized at all.
If you explicitly want to disable default initialization, you can use void as an initializer, as in:
int x = void;
The compiler cannot rely on the stack (or registers) to be zero, so there has to be a instruction to set it to zero anyways.
However, setting a register to zero is a special case and your hardware might be optimized for it.
https://randomascii.wordpress.com/2012/12/29/the-surprising-...
Maybe setting to zero would faster. However, if you optimize on that level, then you can optimize by hand as well. Set it to zero explicitly or even let it uninitialized explicitly: