In part 1 I think nbr is pointless in both snippets. With optimizations turned on there would be no difference in terms of performance.
Should you initialize variables before using std::cin?
Since C++11, if std::cin fails, but is not already in "fail mode", it will set the variable to 0 so if you access the variable afterwards you it won't lead to UB.
1 2 3 4
|
std::cin.clear(); // makes sure cin is not in "fail mode"
int x;
std::cin >> x;
std::cout << x; // Fine. If the read operation failed this will print 0.
|
But if std::cin is already in "fail mode" then it will return immediately without setting the value.
1 2 3 4 5 6 7
|
std::cin.clear(); // makes sure cin is not in "fail mode"
int x;
std::cin >> x;
int y;
std::cin >> y;
std::cout << x; // Fine, as above.
std::cout << y; // UB if the first read operation failed
|
Always initializing the variables seem like the safer option.
1 2 3
|
int age{};
std::cin >> age;
std::cout << "You are " << age " years old.\n";
|
On the other hand,
- someone reading the code might wonder why you are initializing the variable to that particular value (using
{} instead of
= to initialize the variable might make it more obvious the value is unimportant),
- using the value after the read operation has failed is most likely a mistake anyway (you should instead check if it failed and not use the variable in that case), and
- if you run your code through an UB sanitizer it won't tell you something is wrong if you accidentally use the variable (it won't do this in all cases anyway, as we have seen above, but still).
1 2 3 4 5 6 7 8 9
|
int age;
if (std::cin >> age)
{
std::cout << "You are " << age " years old.\n";
}
else
{
std::cout << "I don't know how old you are because you have entered an invalid age!\n";
}
|
Personally I do tend to leave out the initialization if I'm using std::cin (or another std::istream) to give it a value immediately on the next line but it's not primarily a performance concern.