Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable initialization in C++

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; } 
  • What rules, if any, apply to initialization?
  • Specifically, under what conditions are variables initialized automatically?
like image 894
skydoor Avatar asked Feb 07 '10 20:02

skydoor


People also ask

What is variable initialization?

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.

What is variable initialization and why it is important in C?

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.

What is variable declaration and variable initialization in C?

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.

Do variables need to be initialized in C?

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.


1 Answers

It will be automatically initialized if

  • it's a class/struct instance in which the default constructor initializes all primitive types; like MyClass instance;
  • you use array initializer syntax, e.g. 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)
  • same applies to non-aggregate classes/structs, e.g. MyClass instance = {}; (more information on this can be found here)
  • it's a global/extern variable
  • the variable is defined 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++.

like image 156
AndiDog Avatar answered Oct 08 '22 01:10

AndiDog