Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 790
wilbomc Avatar asked Jun 03 '26 18:06

wilbomc


1 Answers

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.

like image 62
Robert Harvey Avatar answered Jun 06 '26 08:06

Robert Harvey