+ 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

8th Sep 2020, 5:08 AM
Yogeshwaran P
Yogeshwaran P - avatar
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; }
8th Sep 2020, 5:12 AM
Josh Greig
Josh Greig - avatar
+ 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.
8th Sep 2020, 5:37 AM
Josh Greig
Josh Greig - avatar
+ 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.
8th Sep 2020, 5:17 AM
NULL
NULL - avatar
+ 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?
8th Sep 2020, 5:26 AM
Yogeshwaran P
Yogeshwaran P - avatar
+ 1
Thank you Josh Greig 😃
8th Sep 2020, 5:41 AM
Yogeshwaran P
Yogeshwaran P - avatar