4

Say I have a variable name len in a function and several strings. Can I use this to store length of those strings one after the other or should I create separate variables? Basically this:

size_t len;
len = string1.size()
....//some code
len = string2.size()
...//more code

versus

size_t str1len, str2len;
str1len = string1.size()
....//some code
str2len = string2.size()
...//more code

All are local variables within a function BTW.

Akilan
  • 151

3 Answers3

6

I would use the same variable name but separate scopes to ensure that I do never accidentally use a length value of the wrong String

{
  size_t len;
  len = string1.size()
  ....//some code
}
{    
  size_t len;
  len = string2.size()
  ...//more code
}
MrSmith42
  • 1,039
  • 7
  • 12
4

If you are really going to introduce those variables as a shortcut for the expressions, and you cannot easily split up that code into two functions, I would definitely go for the second alternative. And I would write it this way:

 size_t str1size = string1.size()
 ....//some code
 size_t str2size = string2.size()
 ...//more code
  • don't use the name "len" when the original name is "size" (will be more consistent in naming)
  • declare and assign in one statement. That will help you to prevent a copy/paste error where you copy the first line down below and forget to change the second variable name.
Doc Brown
  • 218,378
3

Usually it's rather confusing. However the second options you list does not look right either. Instead you should:

  1. For simple things like str.size(), just use that expression where you need it and don't store it in variable at all.
  2. Split the code out to helper functions, so you only process one string in one helper.
  3. At least limit the scope of the variables with a block (see MrSmith42's answer)
Jan Hudec
  • 18,410