+ 1
Please tell me why this code misbehave?
And also tell why the output of first line and second line in console is irrelevant to input values? Why this output come like this? What is the reason for coming output as "32764" in second line? And "0" in first line? Eventhough I enter different values. But third line output come asusual what happening behind it? Please clarify my doubt.... https://code.sololearn.com/cZ83VM0QwJIJ/?ref=app
5 Answers
+ 2
You outputted a and b before they were initialized.
An uninitialized int variable has a completely unknown value. Some call it a garbage value. When I ran, it printed 0 for a but that's unreliable for the next run.
Here is the code as I saw it for reference and in case you edit it after I save my answer here.
#include <iostream>
using namespace std;
int main()
{
int a, b;
int sum;
cout << "Enter a number"<<a<<endl;
cin >> a;
cout << "Enter another number"<<b<<endl;
cin >> b;
sum = a + b;
cout << "Sum is: " << sum << endl;
return 0;
}
This should make more sense to you. Notice that I removed the cout of a before you read the value in using cin. Notice the same for b.
#include <iostream>
using namespace std;
int main()
{
int a, b;
int sum;
cout << "Enter a number"<<endl;
cin >> a;
cout << "You entered: " << a << endl;
cout << "Enter another number"<<endl;
cin >> b;
cout << "You entered: " << b << endl;
sum = a + b;
cout << "Sum is: " << sum << endl;
return 0;
}
+ 2
Yogesh, this might help explain the garbage values: https://www.youtube.com/watch?v=095-FhBO8xE
In short, garbage value is an unreliable, unpredictable value. It is a completely useless value. You can't assume it is even random with any useful random distribution.
+ 1
A couple things:
Youâre asking the function to print (cout) âaâ before it is defined (cin), so you get that trailing 0 after the âEnter a numberâ prompt.
cout << âEnter a numberâ << endl;
cin >> a;
will work fine for the first part.
Secondly, in my experience, the SoloLearn code playground doesnât take multiple inputs very well, meaning your other cin statements are being ignored. This isnât specifically a problem in your code, but when running on SL, you wonât get the desired output. If you have the option available to you, consider learning to compile C++ on desktop rather than mobile.
+ 1
Thank you friends for your explanation.
Based on your explanation I understood how to resolve this problemđ
https://code.sololearn.com/cVks6zZyhtr2/?ref=app
But please tell me what is garbage value?
+ 1
Thank you Josh Greig đ