C语言 在 C 中初始化变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7975008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:03:55  来源:igfitidea点击:

Initializing variables in C

cinitialization

提问by Arthur Collé

I know that sometimes if you don't initialize an int, you will get a random number if you print the integer.

我知道有时如果你不初始化 an int,如果你打印整数,你会得到一个随机数。

But initializing everything to zero seems kind of silly.

但是将所有内容初始化为零似乎有点愚蠢。

I ask because I'm commenting up my C project and I'm pretty straight on the indenting and it compiles fully (90/90 thank you Stackoverflow) but I want to get 10/10 on the style points.

我问是因为我正在评论我的 C 项目,而且我对缩进非常直接,它完全编译(90/90,谢谢 Stackoverflow),但我想在样式点上获得 10/10。

So, the question: when is it appropriate to initialize, and when should you just declare a variable:

所以,问题是:什么时候初始化合适,什么时候应该声明一个变量:

int a = 0;

vs.

对比

int a;

回答by R.. GitHub STOP HELPING ICE

There are several circumstances where you should notinitialize a variable:

有几种情况不应该初始化变量:

  1. When it has static storage duration (statickeyword or global var) and you want the initial value to be zero. Most compilers will actually store zeros in the binary if you explicitly initialize, which is usually just a waste of space (possibly a huge waste for large arrays).
  2. When you will be immediately passing the address of the variable to another function that fills its value. Here, initializing is just a waste of time and may be confusing to readers of the code who wonder why you're storing something in a variable that's about to be overwritten.
  3. When a meaningful value for the variable can't be determined until subsequent code has completed execution. In this case, it's actively harmful to initialize the variable with a dummy value such as zero/NULL, as this prevents the compiler from warning youif you have some code paths where a meaningful value is never assigned. Compilers are good at warning you about accessing uninitialized variables, but can't warn you about "still contains dummy value" variables.
  1. 当它具有静态存储持续时间(static关键字或全局变量)并且您希望初始值为零时。如果您显式初始化,大多数编译器实际上会将零存储在二进制文件中,这通常只是浪费空间(对于大型数组来说可能是巨大的浪费)。
  2. 当您将立即将变量的地址传递给另一个填充其值的函数时。在这里,初始化只是浪费时间,并且可能会让代码读者感到困惑,他们想知道为什么要将某些内容存储在即将被覆盖的变量中。
  3. 当在后续代码完成执行之前无法确定变量的有意义值时。在这种情况下,使用诸如零/NULL 之类的虚拟值初始化变量是非常有害的,因为如果您有一些代码路径从未分配过有意义的值,这会阻止编译器警告您。编译器擅长警告您访问未初始化的变量,但不能警告您“仍然包含虚拟值”变量。

Aside from these issues, I'd say it's generally good practice to initialize your non-static variables when possible.

除了这些问题之外,我认为在可能的情况下初始化非静态变量通常是一种很好的做法。

回答by Timothy Jones

A rule that hasn't been mentioned yet is this: when the variable is declared inside a function it is not initialised, and when it is declared in static or global scope it's set to 0:

一个尚未提及的规则是:当变量在函数内声明时,它不会被初始化,当它在静态或全局范围内声明时,它被设置为 0:

int a; // is set to 0

void foo() {
  int b;  // set to whatever happens to be in memory there
}

However - for readability I would usually initialise everything at declaration time.

但是 - 为了可读性,我通常会在声明时初始化所有内容。

If you're interested in learning this sort of thing in detail, I'd recommend this presentationand this book

如果你有兴趣详细学习这类事情,我会推荐这个演示文稿这本书

回答by Tim Cooper

I can think of a couple of reason off the top of my head:

我能想到几个原因:

  1. When you're going to be initializing it later on in your code.

    int x;
    
    if(condition)
    {
        func();
        x = 2;
    }
    else
    {
       x = 3;
    }
    anotherFunc(x); // x will have been set a value no matter what
    
  2. When you need some memory to store a value set by a function or another piece of code:

    int x;  // Would be pointless to give x a value here
    scanf("%d", &x);
    
  1. 当您稍后在代码中对其进行初始化时。

    int x;
    
    if(condition)
    {
        func();
        x = 2;
    }
    else
    {
       x = 3;
    }
    anotherFunc(x); // x will have been set a value no matter what
    
  2. 当您需要一些内存来存储由函数或另一段代码设置的值时:

    int x;  // Would be pointless to give x a value here
    scanf("%d", &x);
    

回答by Adam Zalcman

Static and global variables will be initialized to zero for you so you may skip initialization. Automatic variables (e.g. non-static variables defined in function body) may contain garbage and should probably always be initialized.

静态和全局变量将为您初始化为零,因此您可以跳过初始化。自动变量(例如在函数体中定义的非静态变量)可能包含垃圾并且应该总是被初始化。

If there is a non-zero specific value you need at initialization then you should always initialize explicitly.

如果在初始化时需要一个非零的特定值,那么您应该始终明确初始化。

回答by anio

If the variable is in the scope of of a function and not a member of a class I alwaysinitialize it because otherwise you will get warnings. 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, alwaysinitialize them to some default, particularly NULL, even if they are to be used later, they are dangerous when uninitialized.

对于指针,始终将它们初始化为某个默认值,尤其是 NULL,即使稍后使用它们,未初始化时也是危险的。

Also it is recommended to build your code with the highest level of warnings that your compiler supports, it helps to identify bad practices and potential errors.

此外,建议使用编译器支持的最高级别警告构建代码,这有助于识别不良做法和潜在错误。

回答by Jared Ng

It's always good practice to initialize your variables, but sometimes it's not strictlynecessary. Consider the following:

初始化变量始终是一个好习惯,但有时并不是绝对必要的。考虑以下:

int a;
for (a = 0; a < 10; a++) { } // a is initialized later

or

或者

void myfunc(int& num) {
  num = 10;
}

int a;
myfunc(&a); // myfunc sets, but does not read, the value in a

or

或者

char a;
cin >> a; // perhaps the most common example in code of where
          // initialization isn't strictly necessary

These are just a couple of examples where it isn't strictly necessary to initialize a variable, since it's set later (but not accessed between declaration and initialization).

这些只是几个例子,在这些例子中,初始化变量并不是绝对必要的,因为它是稍后设置的(但在声明和初始化之间不能访问)。

In general though, it doesn't hurt to always initialize your variables at declaration (and indeed, this is probably best practice).

但总的来说,始终在声明时初始化变量并没有什么坏处(实际上,这可能是最佳实践)。

回答by septical

In general, there's no need to initialize a variable, with 2 notable exceptions:

一般来说,没有必要初始化一个变量,但有两个值得注意的例外:

  1. You're declaring a pointer (and not assigning it immediately) - you should always set these to NULL as good style and defensive programming.
  2. If, when you declare the variable, you already know what value is going to be assigned to it. Further assignments use up more CPU cycles.
  1. 您正在声明一个指针(而不是立即分配它) - 您应该始终将这些设置为 NULL 作为良好的风格和防御性编程。
  2. 如果在声明变量时,您已经知道要为其分配什么值。进一步的分配会消耗更多的 CPU 周期。

Beyond that, it's about getting the variables into the right state that you want them in for the operation you're going to perform. If you're not going to be reading them before an operation changes their value (and the operation doesn't care what state it is in), there's no need to initialize them.

除此之外,它是关于让变量进入您希望它们在您将要执行的操作中所处的正确状态。如果您不打算在操作更改其值之前读取它们(并且该操作不关心它处于什么状态),则无需初始化它们。

Personally, I always like to initialize them anyway; if you forgot to assign it a value, and it's passed into a function by mistake (like a remaining buffer length) 0 is usually cleanly handled - 32532556 wouldn't be.

就个人而言,我总是喜欢初始化它们。如果您忘记为其分配一个值,并且错误地将其传递给函数(例如剩余的缓冲区长度),通常会正确处理 0 - 32532556 不会。

回答by R4D4

There is absolutely no reason why variables shouldn't be initialised, the compiler is clever enough to ignore the first assignment if a variable is being assigned twice. It is easy for code to grow in size where things you took for granted (such as assigning a variable before being used) are no longer true. Consider:

绝对没有理由不初始化变量,如果一个变量被赋值两次,编译器足够聪明,可以忽略第一次赋值。当您认为理所当然的事情(例如在使用之前分配变量)不再正确时,代码很容易变大。考虑:

int MyVariable;
void Simplistic(int aArg){
    MyVariable=aArg;
}

//Months later:

int MyVariable;
void Simplistic(int aArg){
    MyVariable+=aArg; // Unsafe, since MyVariable was never initialized.
}

One is fine, the other lands you in a heap of trouble. Occasionally you'll have issues where your application will run in debug mode, but release mode will throw an exception, one reason for this is using an uninitialised variable.

一个很好,另一个让你陷入麻烦。有时您会遇到应用程序在调试模式下运行的问题,但发布模式会引发异常,原因之一是使用未初始化的变量。

回答by vpit3833

As long as I have not read from a variable before writing to it, I have not had to bother with initializing it.

只要我在写入变量之前没有读取它,我就不必费心初始化它。

Reading before writing can cause serious and hard to catch bugs. I think this class of bugs is notorious enough to gain a mention in the popular SICP lecture videos.

先读后写可能会导致严重且难以捕捉的错误。我认为这类错误臭名昭著,足以在流行的 SICP 讲座视频中提及。

回答by Arun

Initializing a variable, even if it is not strictly required, is ALWAYS a good practice. The few extra characters (like "= 0") typed during development may save hours of debugging time later, particularly when it is forgotten that some variables remained uninitialized.

初始化一个变量,即使它不是严格要求的,也是一个很好的做法。= 0在开发过程中输入的几个额外字符(如“ ”)可能会在以后节省数小时的调试时间,特别是当忘记某些变量仍未初始化时。

In passing, I feel it is good to declare a variable close to its use.

顺便说一句,我觉得声明一个接近其 use 的变量是好的。

The following is bad:

以下是不好的:

int a;    // line 30
...
a = 0;    // line 40

The following is good:

以下是好的:

int a = 0;  // line 40

Also, if the variable is to be overwritten right after initialization, like

此外,如果变量要在初始化后立即被覆盖,例如

int a = 0;
a = foo();

it is better to write it as

最好把它写成

int a = foo();