Hey there,
I just completed problem 1 of projecteuler.net, however as I was working with my code I noticed something odd, which I would love to have explained. If I do not initialize the variable 'result' to a value and run the code, I get result = 1606655790. I realize the problem is line 12, where I have result += i. Since result is not initialized its working off an empty value (?) of itself. I was actually surprised that a number is even spit out, and wanted to know what the computer is doing to arrive at the incorrect solution given above? Another question as well, when I have not set a variable to a value, what does it represent in the computer? Hope I made all of that clear. Thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main()
{
int result = 0;
for (int i = 1; i < 1000; i++)
{
if (((i % 3) == 0) || ((i % 5) == 0))
{
result += i;
}
}
cout << "The sum of the multiples of 3 and 5 below 1000 is " << result << "\n";
}
Uninitialized variables contain some random garbage value, not an empty value, whatever is in the memory location that has been allocated for your variable.
Well first the computer is not arriving a an incorrect solution, the solution is correct, what ever it is.
You have invoked undefined behavior because you didn't properly initialize a variable before you used it. An uninitialized variable can have any value, usually some random leftover value.