简体   繁体   中英

Declaring variables in C/C++

Someone told me: "declaring variables close to their use have value". He corrected me:

void student_score(size_t student_list_size) {
  // int exam;
  // int average;
  // int digit;
  // int counter_digits;

  for (size_t i = 0; i < student_list_size; i++) {
    int exam;
    int average;
    int digit;
    int counter_digits;

I think it's bad, because here variables initialized every loop. What's true?

I encourage to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. And of course, compiler will optimize it.

Both methods would be optimised to the same thing by the compiler. But for readability and ease of future maintenance, declaring the variables within the loop might be preferred by some.

I think it's bad, because here variables initialized every loop. What's true?

The code given the variables are not initialised at all.

So it is just a matter of personal taste.

It depends. C and C++ work differently in that regard. In C, variables MUST be declared at the start of its scope (forget that, it depends on your compiler although it holds true in pre-C99 compilers, as pointed out in the comments - thanks guys!), while in C++ you can declare them anywhere.

Now, it depends. Let's suppose the following two pieces of code:

int i = 0;
while (i < 5) {
    i++;
}



while (i < 5) {
    int i = 0;
    i++;
}

In this case, the first piece of code is what's gonna work, because in the second case you declare the variable at each loop. But, let's suppose the following...

int i = 0;    
while (i < 5) {
    std::String str = "The number is now " + std::to_string(i);
    cout << str << endl;
    i++;
}

In short, declare the variables where it makes most sense to you and your code. Unless you're microoptimizing, like most things, it all depends on context.

First of all that is not valid C code unless you are using -std=c99 .

Furthermore, as long as you aren't creating dangling pointers in the loop, there is no problem with it.

The advantage you gain from doing it this way is that these variables are in a tight knit scope.

This seems like a discussion with many personal opinions, so I'll add mine: I am a C programmer and like the C rules of having to declare your variables at the begining of a function (or block). For one thing, it tells me the stack lay-out so if I create another bug (I do "occassionaly") and overwrite something, I can determine the cause from just the stack lay-out. Then, when having to go through C++ code, I always have to search where the variable is declared. I rather look at the function beginning and see them all neatly declared.

I do ocassionally want to write for (int i=0;... and know the variable goes out of scope following the for loop (I hope it goes out of scope, as it is declared before the block begins).

Then there is an example in another answer:

while (i < 5) {
    int i = 0;
    i++;
}

and I hope it doesn't work because if it works it means there must be a variable i declared before this loop and so you have a clash of variables and scopes which can be horrible to debug (the loop will never terminate because the wrong i is incremented). I mean, I hope all variables must have been declared before their use.

I believe you must have a discipline in declaring your variables. The discipline can vary per person, just as long as it is easy to find where a variable is declared and what its scope is.

You need to know some knowledge of what local variable is ?

A variable declared inside a function is known as local variable . Local variables are also called automatic variables.

Scope : The area where a variable can be accessed is known as scope of variable.

Scope of local variable : Local variable can be used only in the function in which it is declared.

Lifetime : The time period for which a variable exists in the memory is known as lifetime of variable.

Lifetime of local variable : Lifetime of local variables starts when control enters the function in which it is declared and it is destroyed when control exists from the function or block .

void student_score(size_t student_list_size) {
 // int exam;
 // int average;
 // int digit;
 // int counter_digits;

/* The above variable declared are local to the function student_score and can't be used
in other blocks. In your case its the for loop. */

for (size_t i = 0; i < student_list_size; i++) {
 int exam;
 int average;
 int digit;
 int counter_digits;
...
/* The above declared variable are local to the for loop and not to the function.*/

Consider this example:

#include<stdio.h>

void fun();

int main()
{
 fun();
 return 0;
}

void fun()
{
 int i,temp=100,avg=200;
 for (i=0;i<2;i++)
 {
  int temp,avg;
  temp = 10 + 20;
  avg = temp / 2;
  printf("inside for loop: %d %d",temp,avg);
  printf("\n");
 }
 printf("outside for loop: %d %d\n",temp,avg);
}

Output:
inside for loop: 30 15
inside for loop: 30 15
outside for loop: 100 200

If you are declaring the variable in loops the then declare the variable as static (In case if the value of the variable to be saved/used for further iteration).

Even compiler spend lot of time to initialize the variable in loops.

My suggestion is to declare at the beginning of the function. its a good programming practice.

I think, i made my point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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