简体   繁体   English

变量初始化(C#和C ++)

[英]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. 我接受Visual Studio编译器,根据我的理解,默认情况下,如果未事先初始化变量,则会自动将变量初始化为0,但我很好奇最佳实践是什么以及潜在危险(如果有的话)是什么。

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. 虽然我特别指的是VS环境中的C#和C ++语言,但这个问题对所有语言和编译器都是开放的。

the Visual Studio compiler, from what I understand, automatically initializes variables to 0 by default if they are not initialized before hand 根据我的理解,Visual Studio编译器默认情况下会自动将变量初始化为0,如果它们未事先初始化的话

Not always. 不总是。

Scope matters. 范围很重要。 Private members of the class are automatically assigned their default values, but locally-scoped variables (ie declared in a method) are not. 该类的私有成员会自动分配其默认值,但本地范围的变量(即在方法中声明)不是。 out parameters are not automatically assigned. out参数不会自动分配。 Value and Reference parameters are always assigned (they either get passed in a value, or a default value is declared). 始终赋值Value和Reference参数(它们要么传入值,要么声明默认值)。

C# will let you assign a value after the declaration, but will not allow you to reference variables that are not assigned. C#会让你的声明之后指定值,但不会让你引用一个未分配变量。

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: 如果你有一个庞大的变量列表我通常使用一个大的equals语句:

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 . 它除了更大的C ++理念总是在任何时候存储在您的变量的值。

Initialization statements as int value = 0; 初始化语句为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). 它消除了由于未初始化的变量引起问题的可能性(在这种情况下不是一种做法,以避免在需要初始化的许多其他情况下出现问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM