wilbomc
wilbomc

Reputation: 183

Variable initializing (C# and C++)

Quick question, is it good practice to initialize all "blank or empty" variables when it has not to carry either positive or negative values, for example using this:

int value = 0;

instead of:

int value;

I accept the Visual Studio compiler, from what I understand, automatically initializes variables to 0 by default if they are not initialized before hand but I am curious as to what the best practice is and what the potential hazards (if any) are.

Although I am referring to the C# and C++ languages within the VS environment particularly, this question is open to any languages and compilers across the spectrum.

Upvotes: 3

Views: 4058

Answers (3)

Robert Harvey
Robert Harvey

Reputation: 180868

the Visual Studio compiler, from what I understand, automatically initializes variables to 0 by default if they are not initialized before hand

Not always.

Scope matters. Private members of the class are automatically assigned their default values, but locally-scoped variables (i.e. declared in a method) are not. out parameters are not automatically assigned. Value and Reference parameters are always assigned (they either get passed in a value, or a default value is declared).

C# will let you assign a value after the declaration, but will not allow you to reference variables that are not assigned.

Upvotes: 7

Yogendra Singh
Yogendra Singh

Reputation: 34387

Initialization statements as int value = 0; are more preferable and good programming practice for two reasons.

  1. Its better from readability perspective

  2. It removes the possibility of issues due to uninitialized variables(not in this case but a practice to avoid issues in many other cases where initialization is required).

Upvotes: 1

Syntactic Fructose
Syntactic Fructose

Reputation: 20104

It is always good practice to initialize variables to prevent undefined behavior later in the program. Some later compilers might do this for you, but at the lower lever not defining a variable CANNOT be caught by the compiler and can lead to some very painful headaches. If you have a massive list of variable i usually use a big equals statement:

int a,b,c,d,g;
a=b=c=d=g=0; //set all to zero

it's apart of the bigger c++ philosophy to always have a value stored in your variable at all times .

Upvotes: 3

Related Questions