No idea whats wrong

Jun 28, 2022 at 7:15am
I have an issue with code output being not what i want it to be and its different in different IDEs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>
using namespace std;

int main()
{
	
	int test[5];
	int i,total;
	
	for(i=0;i<5;i++)
	{
	cin >> test[i];
	total=total+test[i];
	}
	
	cout<<endl<<endl;
	for(i=0;i<5;i++)
	cout<<test[i] <<endl;
	
	cout<<total;
	
	
	return 0;
}


When i run this code in DevC++ , and I input 10 ... 5 times, the total should be 50 but somehow in DEVC++ it will add extra 1 to the output so cout<<total is 51 instead. And if i copy this exact code to another IDE Embarcadero C++, with same input 10 ... 5 times, the output is 66

1) This issue is fixed when i initialize total=0 but I am curious why it worked in my lecturer's computer ( its recorded lecture and she did not initialize total=0 and she got the correct output which is 50.
2) Why is it different output in different IDEs?
Jun 28, 2022 at 7:22am
Using an uninitialized variable leads to undefined behaviour (UB) which means there are no guarantees what will happen.
Last edited on Jun 28, 2022 at 8:29am
Jun 28, 2022 at 7:25am
If you don't initialize a variable it has random value. On your PC it was 1, on her computer is was 0...
Topic archived. No new replies allowed.