Ah. I think I understand now. Thank you very much for the examples and the explanations. (Though, I'm way too low of a level to be able to comprehend citizen's example, but it helps that he gives me an example where "else if" is quite necessary and isn't simply a matter of efficiency)
I was experimenting, and there's something that I want to run by you guys once more. I created a (rather sloppy) program, and found something interesting.
Code:
#include <stdio.h>
int main()
{
int x;
printf ("Insert a number between 1-3: ");
scanf ("%d", &x);
if (x == 1)
printf ("x is one.");
else if (x == 2)
printf ("x is two.");
else if (x == 3)
printf ("x is three.");
else
printf ("x is not one, two, or three.");
return 0;
}
Input: 1 --> x is one
Input: 2 --> x is two
Input: 3 --> x is three
Input: 4 --> x is not one, two, or three.
I also tried changing all of the "else if" statements to "if" statements, and it gave me different results:
Input: 1 --> x is one.x is not one, two, or three.
Input: 2 --> x is two.x is not one, two, or three.
Input: 3 --> x is three.
Input: 4 --> x is not one, two, or three.
It seemed really peculiar, but when I looked at MacGyver's explanation of how ifs/thens are expanded, it makes sense. It goes something like this, right?
Code:
if(x == 0) ....
else if(x == y) ....
else if(x == z) ....
else ....
expands to...
Code:
if (x == 0) ....
{
....
}
else
{
if (x == y)
{
....
}
else
{
if (x == z)
{
....
}
}
}
This seems consistent with my example programs. In the "else if" version, if '1' or '2' is the input, then it will skip all of else(/ifs) after it, which is why, when given '1' or '2', it gives "x is 1 (or 2)" as the output without the "x is not one, two, or three" string after it. It looks to me like a tree of if/thens. The first "if" has a branch, which is the first "else if," and this "else if" has another branch, which is another "else if," etc. However, with the "only if" version, all three "ifs" are on different parts of the tree, which would explain why it gives me an output like "x is one.x is not one, two, or three." The "only if" version evaluates all three of the conditions. With '1,' it evaluates "if (x == 1) as true, so it proceeds with that. if(x == 2) is false, so it skips it, and if(x == 3) is also false, which explains why it goes to the "else" statement. (It looks like in this scenario, the else statement belongs to the if(x == 3) branch because it comes right after it). This seems like a delicate subject because I'm so early on (You don't want to build a house on a faulty foundation, right?), so I wanted to make sure that I have my ideas on the right track.
Again, I am very thankful.