Declaring Variables in C / C ++

Someone told me: "Declaring variables close to their use matters." 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 this is bad, because here the variables initialized each loop. Really?

+4
source share
7 answers

I recommend declaring them as local as possible, and as close as possible to the first use. This makes it easier for the reader to read the declaration and shows what type of variable and that it was initialized. And, of course, the compiler will optimize it.

+5
source

. .

+3

, , . ?

, , .

.

+3

. C ++ -. C (, , pre-C99, - , !), ++ .

. , :

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



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

, . , ...

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

, , . , , .

0

, C, -std=c99.

, , , .

, , , .

0

, : C , C, ( ). -, , , ( " " ) - , . , ++, , ​​. , .

(int = 0;... , for ( , , ​​ ).

:

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

, , , , i, , ( , ). , , .

, . , , , ​​ .

0

, ?

, , . .

. , , .

: , .

: , , .

: , , , , .

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.*/

:

#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

, static ( , / ).

.

- . .

, .

-1

Source: https://habr.com/ru/post/1569268/