Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the benefit of initializing your variables late in the function than at the start of a function body?

Tags:

c++

variables

Ive been reading a excellent book written by Bjarne Stroustrup and he recommends that you declare variables as late as possible, preferable just before you use it, however it fails to mention any benefits over declaring the variables late than at the start of the function body.

So what is the benefit of declaring variable late like this:

int main()
{
  /* some
     code
     here
  */
  int MyVariable1;
  int MyVariable2;
  std::cin >> MyVariable1 >> MyVariable2;
  return(0);
}

instead of at the start of a function body like this:

int main()
{
  int MyVariable1;
  int MyVariable2;
  /* some 
     code
     here
  */
  std::cin >> MyVariable1 >> MyVariable2;
  return (0);
}
like image 548
Harry the hacker Avatar asked Dec 03 '25 13:12

Harry the hacker


1 Answers

It makes the code easier to follow. In general, you declare variables when you need them, e.g. near a loop when you want to find a minimum of something via that loop. In this way, when someone reads your code, (s)he doesn't have to try to decipher what 25 variables mean at the start of a function, but the variables will "explain" themselves when going through the code. After all, it's not important to know what variables mean, but to understand what the code does.

Remember that most of the time you use that local variable in a very small portion of your code, so it makes sense to define it in that small portion where you need it.

like image 90
vsoftco Avatar answered Dec 05 '25 01:12

vsoftco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!