0

When do I need to initialize variables in c++? Some people assert that its important but maybe this is more an issue in c-language?

I am refferering to primitives i.e. char, int, long, double

Let say I have the following code-snippet

 int len; 
 double sum, mean;
 char ch;

 while (true) {

    // here I use these primitives where they are initialized.


 }

So - should I initialized these primitives as a good programming pratice here?

user2991252
  • 760
  • 2
  • 11
  • 28
  • 2
    You don't need to as long as they aren't uninitialized when you use them, but some people prefer to initialize everything when declared. In my experiences, the compiler will usually warn if you forget to set them to something. – chris Apr 16 '14 at 15:42
  • I prefer to initialize them right away. I have bad memories with an uninitialized boolean and ignoring the compiler warning about it. – Adri C.S. Apr 16 '14 at 15:46
  • 1
    "When do I need to initialize variables in C++?". When you want your program to function as you expect. – Throwback1986 Apr 16 '14 at 15:56
  • Check this question: http://stackoverflow.com/questions/6032638/default-variable-value – Pablo Francisco Pérez Hidalgo Apr 16 '14 at 15:57
  • As a note, I think most code profilers will throw warnings/errors when analyzing non-initialized member variables. There's really no reason *not* to initialize them right away; the memory has already been allocated. – MrDuk Apr 16 '14 at 16:12

4 Answers4

2

The problem is, of course, the use of unitialised variables as in

int x;
int y=1+x; // oops what is y?

AFAIK, the language standard allows the compiler to initialise x to 0, but also to leave it unitialised. In any case, most optimisations (-O) will omit an initialisation in the above situation.

If you use full warning compiler flags (e.g. -Wall -Wextra -pedantic) the compiler will almost certainly spot the usage of unitialised variables (it will also warn about usage of unitialised variables in library header files, such as boost headers -- the boost developers appear to not use such useful diagnostics).

In general, whether or not to initialise all variables is a matter of style. I would provide an explicit initialisation whenever there is a sensible initial value for a variable and/or if there is the danger of it being used unitialised. Different from C, the possibility of unitialised variables is quite rare in C++, in particular when passing by return value (including move semantics).

Walter
  • 44,150
  • 20
  • 113
  • 196
  • _In general, whether or not to initialise all variables is a matter of style._ Initializing all variables is a well accepted guideline in C++, see chapter 19 in Sutter & Alexandrescu - C++ Coding Standards. I wouldn't just call it a matter of style. – D Drmmr Apr 16 '14 at 18:50
  • @D Drmmr Doesn't the compiler warn you if you set a variable to a value, set it to another value and consequently never use the first value? Or am I thinking of another language/compiler... – Mdev Apr 16 '14 at 19:20
2

In c++ compiler usualy do not initialize local (automatic) variables. These variables are created on the stack and they are filled with random values. Usualy you do not need to inicialize variables but read carefuly what the compiler says. Try:

int main() {
int x;
x=x+1;
}

and compile it with -Wall switch (I'm using gcc). When the message

x.cpp: In function ‘int main()’:
x.cpp:3:6: warning: ‘x’ is used uninitialized in this function [-Wuninitialized]
x=x+1;

is written, then it would be better to initialize such variable.

  • They're not actually filled with random values, they're garbage values from whatever was at that address before. So if you run something twice where a variable is used uninitialized then initialized in each run, you might see values like run 1: 6114423, 1 ... run 2: 1, 1 because the address used for the variable happened to be at the same address used in the last run and it just used what was there. At least, I'm pretty sure this is how it works. – Mdev Apr 16 '14 at 19:18
1

You should initalize all variables to prevent: "trash in input - trash in output".

Over Killer
  • 507
  • 9
  • 24
1

When do I need to initialize variables in c++?

You should initialize local variables with a sensible value when you define them. If you cannot give a variable a sensible value yet, then you should probably define it later.

The goal here is to minimize the amount of state in your functions in order to make them easier to understand. When all variables are defined at the beginning of the function, you don't know what they are used for. When they are defined at the point they are needed, it's clear that they are not used before that point. This also helps to limit the scope in which variables are declared (e.g. inside the loop instead of before it, thus less state outside the loop) and it allows you to define more variables as const (thus not adding state).

D Drmmr
  • 1,223
  • 8
  • 15