Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ double initialization- default values?

Tags:

c++

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?

like image 601
Noble-Surfer Avatar asked Jul 12 '26 06:07

Noble-Surfer


1 Answers

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.

like image 112
Some programmer dude Avatar answered Jul 13 '26 20:07

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!