Always initialize variables in C

Some programmers say that you should always declare all variables at the beginning of a sequence (functions) first in C, although this is no longer necessary since C99. Is it also a good idea to initialize all the variables at the beginning or is it a waste of CPU time?

+3


source to share


5 answers


Some programmers say that you should always declare all variables at the beginning of a sequence (function) first in C ...

I find that declaring variables close to where they are used is better. @ pm100

But that's a style issue. Better to follow the batch coding standard.

Also is it a good idea to initialize all the variables at the beginning or is it a waste of cpu time?

With simple variables, this is not a "waste of CPU time".

With long arrays, there is little chance of significant latency.



#define N 4096
char buf[N];
// or
char buf[N] = { 0 };
if (fread(buf, sizeof buf[0], N, ...

      

Perform "unnecessary" initialization with the group coding standard.

Consider 4 cases: 3 have potential UB

// No initialization
char buf1[N];
fgets(buf1, sizeof buf1, stdin);
fputs(buf1, stdout);

// Initialization
char buf2[N] = {0};
fgets(buf2, sizeof buf2, stdin);
fputs(buf2, stdout);

// No initialization, early assignment
char buf3[N];
buf3[0] = '\0';
fgets(buf3, sizeof buf3, stdin);
fputs(buf3, stdout);

// No initialization, test function result that populates buf4
char buf4[N];
if (fgets(buf4, sizeof buf4, stdin)) {
  fputs(buf4, stdout);
}

      

Only if (fgets(buf4, sizeof buf4, stdin))

is proper protection against read error that ends with "array contents undefined".

I am not criticizing or discarding unnecessary initialization as 1) compilers often (not always) detect and warn about missing initialization / assignment. 2) Coding problems that I see tend to exist without considering error status and 3) as with holy war problems like indentation style , I follow the group coding standard - whatever it is.

+3


source


In general, yes, it is always better to choose variable initialization (local cloud, automatic storage in particular) by definition. This avoids the possibility of using unified values, which can lead to undefined behavior.

For example, a simple case,

int x;

//...after some code
if (/*some options*/) x = 0;

//after some more code

if (x == 5) {....

      

the snippet above can certainly lead to UB if the value if

is false. However, by determining x

if we initialize, for example

 int x = -1;

      



then at least we can avoid UB.

Note. This does not justify ignoring the compiler warning (using a unified variable is possible), although this is just an example.

However, with proper optimization, it doesn't matter to the compiler where you define your variable, but for the purpose of readability, you should always define variables that are close to / before using them. This is again a recommendation, not a rule.

There's a good Q&A on SE software , read this.

+2


source


You are confusing initialization with declaration. Initialization gives a variable its initial value, and if you can, this is good style for initializing variables. You must assign a value to the variable before using it anyway.

But your question seems to be about where to declare the variables. Generally accepted best practice is as close to use as possible.

Since C89, variables must be declared at the beginning of a block. The only reason I could think of sticking to this rule (not being compatible with a very old standard) is because it encourages you to keep your functions and blocks short. But I'm not a big fan of such arguments because you can still keep functions and block short (definitely good practice) by declaring variables only when they are actually used, which makes the code a little better readable.

+1


source


Compilers are smart enough to optimize your code, whether you define variables at the beginning or in the middle of a code region.

In many cases, defining a variable at the right time looks more readable, since you can easily keep track of which type of variable and which variable is being used (especially with a very long piece of code).

However, initializing variables as soon as it is defined is good behavior, as it helps avoid undefined behavior due to access to uninitialized variables.

+1


source


Just to indicate a dissonant view (I agree that initialization is good).

When a variable will be used as a counter in a loop for

, I find that initialization looks worse than assignment

int i = 0;              // initialization
for (; i < 100; i++) {
    // code, code, code
    if (foo == bar) i = 999;
    // code, code, code
}
if (i == 999) exit(EXIT_FAILURE);

      


int i;
for (i = 0; i < 100; i++) { // assignment
    // code, code, code
    if (foo == bar) i = 999;
    // code, code, code
}
if (i == 999) exit(EXIT_FAILURE);

      

+1


source







All Articles