2

Consider following program (See live demo here)

import std.stdio;
void main()
{
   int i=int();
   writefln("i is %d",i);
}

In language like C++ the statement int i=int(); is known as value initialization. For the type int, value initialization basically ends up being zero initialization. If I am not wrong C++ standard guarantees that it gives me zero always. But is D language contain feature like value initialization as we have in C++? Is it necessarily give me a zero on all D compilers & on every environment where I compile & run above D program?

Puppy
  • 144,682
  • 38
  • 256
  • 465
Destructor
  • 14,123
  • 11
  • 61
  • 126

2 Answers2

7

When a variable is declared in D, it is always set to its 'default initializer', which can be manually accessed as T.init where T is the type (ex. int.init). The default initializer for integer types is 0, for booleans false, and for floating-point numbers NaN.

So you don't even need to assign to a variable for default initialization; just declaring it is fine. int i; will always be zero until set to something else.

Default initialization can be explicitly disabled by initializing the variable to void; for example, int i = void;.

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
  • But http://www.tutorialspoint.com/d_programming/d_programming_variables.htm says that "For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.". & in my program variable is having automatic storage duration. – Destructor Oct 25 '15 at 05:20
2

In D any value is initialized, it will here always give the default value for an integer: 0. It is way safer than in C++ where initialization occurs only if it can be done at no cost.

cym13
  • 799
  • 5
  • 10
  • Only if it can be done at no cost? Tell that to `std::vector`. – chris Oct 24 '15 at 18:10
  • @chris What type from C++ has to do with D? – sigod Oct 24 '15 at 18:29
  • 1
    Note: you can use `int i = void;` when you want uninitialized value. – sigod Oct 24 '15 at 18:30
  • @sigod, I gave a counterexample to the statement in the answer: *It is way safer than in C++ where initialization occurs only if it can be done at no cost.* – chris Oct 24 '15 at 18:37
  • @chris I will admit my ignorance of std::vector internals, C++ is complex and I merely wanted to give a rule of thumb :) – cym13 Oct 25 '15 at 19:21