Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are variables initialized to 0?

Tags:

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?

like image 672
Ergo Proxy Avatar asked Aug 03 '13 08:08

Ergo Proxy


1 Answers

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.

like image 69
Konrad Rudolph Avatar answered Dec 01 '22 07:12

Konrad Rudolph