Arthur Collé
Arthur Collé

Reputation: 2607

Initializing variables in C

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

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.

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

int a = 0;

vs.

int a;

Upvotes: 24

Views: 105885

Answers (10)

Adam Zalcman
Adam Zalcman

Reputation: 27233

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.

Upvotes: 5

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215607

There are several circumstances where you should not initialize a variable:

  1. When it has static storage duration (static keyword 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 you if 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.

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

Upvotes: 40

R4D4
R4D4

Reputation: 1402

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.

Upvotes: 2

Arun
Arun

Reputation: 20403

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.

In passing, I feel it is good to declare a variable close to its 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();

Upvotes: 0

vpit3833
vpit3833

Reputation: 7961

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.

Upvotes: 1

anio
anio

Reputation: 9171

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

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.

Upvotes: 5

Timothy Jones
Timothy Jones

Reputation: 22165

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:

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 presentation and this book

Upvotes: 32

septical
septical

Reputation: 440

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.

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.

Upvotes: 2

Jared Ng
Jared Ng

Reputation: 5071

It's always good practice to initialize your variables, but sometimes it's not strictly necessary. 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).

Upvotes: 4

user142162
user142162

Reputation:

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);
    

Upvotes: 5

Related Questions