Effective C++ item 26: Postpone Variable Definitions As Long As Possible

This rule is very obvious. Instead of

1
2
3
4
5
6
7
8
9
10
11
std::string encryptPassword(const std::string& password)
{
using namespace std;
string encrypted;
if (password.length() < MinimumPasswordLength) {
throw logic_error("Password is too short");
}
... // do whatever is necessary to place an
// encrypted version of password in encrypted
return encrypted;
}

We should define encrypted right before we need to use it

1
2
3
4
5
6
7
8
9
10
11
std::string encryptPassword(const std::string& password)
{
using namespace std;
if (password.length() < MinimumPasswordLength) {
throw logic_error("Password is too short");
}
string encrypted;
... // do whatever is necessary to place an
// encrypted version of password in encrypted
return encrypted;
}

Another common question is which way is better looking at following examples of doing for loop

1
2
3
4
5
6
7
8
9
10
11
// example 1
Widget w;
for (int i = 0; i < n; ++i){
w = some value dependent on i;
...
}
// example 2
for (int i = 0; i < n; ++i) {
Widget w(some value dependent on i);
...
}

The answer is always use the second approach unless performance is critical to your application. If performance is your main requirement, you need to compare which one is cheaper to execute between 1 constructor + 1 destructor + n assignments for example 1 and n constructors + n destructors for example 2.

Reference:
“Effective C++” Third Edition by Scott Meyers.