I'm watching a video tutorial for C++, and this is a minor issue because I still got the program to work. But as it was explained to me, typing else if would make the program skip those pieces of code if they turned out to be unnecessary. Going through the debug program I noticed that the program was still checking these else if parts so I'm wondering what went wrong. I'm using Eclipse Kepler if it makes any difference at all.
I shortened it for convenience but that's the gist of it.
As a side question, how many years ago would be considered outdated in C++? The tutorial videos are from 2011 and I don't know exactly how quickly the language changes. Thanks for advance for any information you can give me.
else if's are only checked if everything above them returns false. Once anything in a chain of if and else if statements returns true the rest are skipped.
You can observe by making a small change toy your program and supplying the input "91"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{
int score = 0;
cout << "Enter an integer score between 0 - 100." << endl;
cin >> score;
if(score >= 90 && score <= 100)
{
cout << "Awesome!" << endl;
}
elseif(score >= 80 && score <= 89 || score==91)//I changed this line
{
cout << "Well Done." << endl;
}
return 0;
}
Now inputting 91 will still only print "Awesome!". Because the first if statement returned true, all else if's below are ignored.
The work is done only if the condition is true. The condition has to be evaluated.
The next form has two branches:
IF condition THEN yeswork ELSE nowork
Condition is always evaluated, but only one of the branches is evaluated.
Now, replace the nowork with simpler 'if':
IF conditionA THEN Awork ELSE (IF conditionB THEN Bwork)
conditionA is always evaluated. Then one of the two branches starts. If it is the "nowork" branch, then the conditionB is definitely evaluated. It is possible that neither Awork nor Bwork is done.
Thank you both for your quick replies, I'll be honest and say I'm still a bit lost, I started learning yesterday so a good amount of the terminology still escapes me. I think I might take a break and look at it later (I'm sorry I must sound absolutely dense to everyone who's been doing this a long time).