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.
3
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.
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
}
8
Usually it’s rather confusing. However the second options you list does not look right either. Instead you should:
- For simple things like
str.size()
, just use that expression where you need it and don’t store it in variable at all. - Split the code out to helper functions, so you only process one string in one helper.
- At least limit the scope of the variables with a block (see MrSmith42’s answer)