Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variables in C/C++

Tags:

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?

like image 863
rel1x Avatar asked Dec 25 '22 00:12

rel1x


1 Answers

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.

like image 79
wanillsky Avatar answered Jan 20 '23 00:01

wanillsky