The name of this is initialization. So you initialize the variable:
int sum = 0;
That is, initialization occurs when you declare a variable already assigning it an initial value.
In other words, you declare it without initializing:
int sum;
On your for
, you have this:
sum = sum + die1[i] + die2[i];
That is, it modifies the value of sum
based on the previous value. But in the first iteration of this for
, if you declared sum
without initializing, what would be the first value of it?
The answer is that the initial value of it is anything . Often this "anything" is zero, but it may not be. Often this value is called by the affectionate name of " garbage ".
Okay, but maybe you're wondering, why does C have such bizarre behavior? The answer lies in how memory is organized.
In C, each variable is allocated somewhere in memory. When a program is running, a certain part of it can use some portion of memory to do something, and as soon as it finishes, it releases that portion of memory. The release is not clearing. The old values of the function / procedure / some-other-thing that ended are dropped there in memory. After some time, another part of the program allocates that memory region (which is dirty) again and starts to use it.
That is, what happens is that the original content of the
sum
variable is dirty, and contains information that is remainder of some other part of something else that was using that piece of memory for some other purpose.
And so, comes the question: Why is it not cleaned when the sum
variable is allocated? The answer is because this is almost always unnecessary. This is what initialization is for. Initialization is not only to define what the initial value of the variable is, but also to erase / overwrite any garbage there. And then you ask, and why is not he cleaned anyway? The answer is because this would mean that it could end up being cleaned twice, one automatically and one by initialization or by first assigning a variable value, which means that if the compiler generated code to automatically clean the variable before using it, the result would be a waste of performance.
And why did anyone who used it last, did not leave it clean? The answer is because this code, whatever it is, did not have it cleaned! And cleaning should be unnecessary, since anyone who uses that part of memory later probably would / should overwrite their content with something else.
In conclusion, using dirty memory values is a bad programming practice, it is considered a bug. In practice, one can not know for certain what the old value is, and whatever it is, it would probably not be any useful value. This value is rubbish, dirt, something we know nothing about and can not control and therefore is useless. Never use dirty memory values.
Finally, a number of code analysis tools will generate alerts warning that the sum
variable may not be initializing properly - Maybe the compiler itself is giving you a warning warning of this problem.