My understanding is that an int
variable will be initialized to 0
automatically; however, it is not. The code below prints a random value.
int main () { int a[10]; int i; cout << i << endl; for(int i = 0; i < 10; i++) cout << a[i] << " "; return 0; }
Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.
This refers to the process wherein a variable is assigned an initial value before it is used in the program. Without initialization, a variable would have an unknown value, which can lead to unpredictable outputs when used in computations or other operations.
The main purpose of variables is to store data in memory. Unlike constants, it will not change during the program execution. However, its value may be changed during execution. The variable declaration indicates that the operating system is going to reserve a piece of memory with that variable name.
Even if this variable will be used later I prefer to assign it on declaration. As for member variables, you should initialize them in the constructor of your class. For pointers, always initialize them to some default, particularly NULL, even if they are to be used later, they are dangerous when uninitialized.
It will be automatically initialized if
MyClass instance;
int a[10] = {}
(all zeroed) or int a[10] = {1,2};
(all zeroed except the first two items: a[0] == 1
and a[1] == 2
)static
(no matter if inside a function or in global/namespace scope) - thanks Jerry Never trust on a variable of a plain type (int, long, ...) being automatically initialized! It might happen in languages like C#, but not in C & C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With