+ 1

This makes no sense [solved]

I'm trying to solve the code coach problem but it's not working for some mysterious reason. And I tried to debug it. And now this code says that there is no output when, I swear, there should be. Delete the line that says: "check += things;" to see the difference. https://code.sololearn.com/cf4EilG68s1q/#cpp

1st Jan 2020, 5:04 PM
CeePlusPlus
CeePlusPlus - avatar
6 Answers
+ 7
Why isn't your 'i' initialized.
1st Jan 2020, 5:25 PM
Avinesh
Avinesh - avatar
+ 3
Avinesh i never knew that was the problem! I didn’t initialize it because ‘i’ automatically becomes 0, or I thought it did. Sometimes for loops work without intializing the variable but not in this case. Anyways, thanks!
1st Jan 2020, 5:28 PM
CeePlusPlus
CeePlusPlus - avatar
+ 3
You don't need initialize global or static variable, but you should have initialize any local variables
1st Jan 2020, 10:53 PM
electron
electron - avatar
+ 2
"Sometimes" Undefined behaviour likes to slap you in the face when you least expect it.
1st Jan 2020, 6:14 PM
Dennis
Dennis - avatar
+ 2
As mentioned by those before me, you didn't initialize your 'i' in your for loop. It is not an error per say, but it is dangerous. Depending on the os, it can be anything. Some OS, when a variable is given an address, will give the value of what was previously there. Other OS might put the maximum value for the type or maybe zero. Which is why we call it an undefined behaviour. Always give a known value to your variables when initializing them, or else get junk! If explicitly writing "int i = 0;" is to tedious, you can also write "int i{};" which is identical but more generic since you can use this for any type, but you sacrifice some readability.
2nd Jan 2020, 4:43 AM
Jean-Philip Sabourin
Jean-Philip Sabourin - avatar
+ 1
CeePlusPlus works fine now👍
1st Jan 2020, 5:29 PM
Avinesh
Avinesh - avatar