Reputation: 361
I just started studying C++ from an ebook.
I don't have any errors on my code but I do have a question.
The book uses the following code to sum up two numbers:
#include <iostream>
int main()
{
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
return 0;
}
So int v1 = 0,v2 = 0;
is used for variables.
Why are they initialized to 0?
Upvotes: 21
Views: 1988
Reputation: 545528
It’s cargo cult programming. It isn’t actively harmful but it serves no real benefit here and is likely only done because either the author wants to simplify a concept for teaching purposes, or because he misunderstood something.
Here’s why.
Normally, all variables should be directly initialised once declared. This ensures that the variable is never in an indeterminate state. This makes the control flow simpler, the code easier to reason about and as a consequence prevents bugs.
But this only makes sense if we can initialise the variables with a meaningful value – i.e. with the value it’s meant to represent later. In your code, this isn’t the case – rather, the variables get their value assigned later, via input streaming (unfortunately C++ doesn’t support a concise, canonical way of initialising a variable with a value read from input).
As @jrok said, the initialisation ostensibly guards against invalid inputs and subsequent errors in the code. I say ostensibly because that’s not actually true: the value we initialised the variables with – 0
– is also invalid in the context of the program so we haven’t actually gained anything.
Jack Aidley offers that the real reason for this code is to prevent a compiler warning. But no compiler should warn here, for the reason outlined above. And in fact, GCC doesn’t warn, even when compiled with lots of warnings enabled. Maybe other compilers do but I would consider this warning noise.
Upvotes: 22
Reputation: 55395
int v1 = 0;
That's called initialization and it's a good habit to get in to. If you leave out the initializer for built in types, its value is called to be indeterminate and it's illegal to read such a value.
Let's suppose you do this:
int v1;
std::cin >> v1;
std::cout << v1;
Input operation in the second line can fail, for example if you enter a letter instead of a number, and v1
will be left untouched. There is no check whether input succeeded and if v1
still happens to uninitialized, bang! You've invoked undefined behaviour and you're left at the mercy of the compiler to do just about anything it wants.
In the code you posted, v1
and v2
are initialized and even if input fails, you'll at least get some result with well defined behaviour.
That said, it's a logical error to not check whether input suceeded. After all, 0
is a valid input possibilty and without an additional check there's no way to tell if that's what user entered.
The easiest way to do that is to use input expression in boolean context, inside if
condition:
if (std::cin >> v1 >> v2) {
// good, use v1 and v2
} else {
// bad input, we can't
// rely on v1 and v2 to
// have meaninful value here
}
Streams are implicitly convertible to bool
and if there are no error flags set, they evaluate to true
and to false
otherwise.
Having done the above check there's little to no need for initialization, as we'll never touch v1
and v2
if input failed.
Upvotes: 14
Reputation: 2221
It's part of a common practice.
It is better to initialize a value to a variable to give it a sense of completeness.
Upvotes: -1
Reputation: 20107
While the other answers are correct, I don't believe they are likely to be the actual reason why these variables are being initialised to zero.
Instead, I strongly suspect the reason is this: if they were not, most compilers would issue a warning about using an uninitialised variable. I believe the initialisation here is there primarily, or purely, to suppress the issuing of a warning.
Upvotes: 0
Reputation: 76245
It's a common practice, but in this example it's a workaround for not having thought enough about error handling. The rationalization that you could get an invalid value if you don't initialize them only matters if you don't bother to check whether the input succeeded. The code doesn't check whether the input succeeded, so it is fatally flawed. No amount of otherwise unneeded initialization can fix that.
std::cin >> v1 >> v2;
if (std::cin)
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
else
std::cout << "Bogus input\n";
Upvotes: 13
Reputation: 13792
It's a common practice to set a value to the variables when you define them. Sometimes, you get bad errors when try to operate with variables that weren't initializated with a value.
But in your example, it isn't important, because you set a value with cin read.
Upvotes: 1