6

I'm debugging some C++ code, and have come across a double that never appears to have been given a value. It is declared with the line

double x;

Having not used C or C++ much before, I'm unsure whether doubles have a value that they default to? I.e. Given the declaration above, if x is never specifically given a value, will it automatically be 0, or will it be null?

The x is used in a calculation elsewhere in the code, and the result of the calculation is meant to be displayed to the user - at the moment it's not... The calculation is:

y * asin(sin(x / y) * sin(a * b));

I would assume that if x defaults to 0, this would cause a compile/runtime error? If x defaults to 0, surely the calculation would return 0, and 0 would be displayed to the user?

Augustin
  • 2,444
  • 23
  • 24
Noble-Surfer
  • 3,052
  • 11
  • 73
  • 118

3 Answers3

13

It depends on where the variable is declared.

If it's declared as a global variable then it will be zero-initialized before main starts running.

If it's declared as a non-static local variable inside a function then its value is indeterminate (in reality it will be whatever is in the memory occupied by the variable, it will be seemingly random).

Using uninitialized (non-static) local variables leads to undefined behavior.

If declared as a static local variable, then it will also be zero-initialized in the first call to the function.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
7

If you don't specify an initialization value then the value for double x is undefined if it's on the heap/stack. If it's a global variable it will be set to 0.

Sean
  • 60,939
  • 11
  • 97
  • 136
1

Zero initialization is performed in the following situations:

  1. For every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization.
  2. As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided.
  3. When an array of any character type is initialized with a string literal that is too short, the remainder of the array is zero-initialized.

https://en.cppreference.com/w/cpp/language/default_initialization

https://en.cppreference.com/w/cpp/language/zero_initialization

So double data members in classes with no constructors will be initialized to zero.

Community
  • 1
  • 1