Originally Posted by
russiancircles
I actually did try switching places between the else if and the else-command, didn't seem to work, maybe it was because i used string instead of int?
It didn't work because it is syntactically incorrect. Every else must have a matching if, so this:
Code:
if (user_age_1 < user_age_2)
{
cout << "user number 2 is older than user number 1" << "\n";
}
else
{
cout << "user number 1 is older than user number 2" << "\n";
}
else if (user_age_1 > 100 && user_age_2 > 100)
{
cout << "both users are over a 100 years old" << "\n";
}
is equivalent to:
Code:
if (user_age_1 < user_age_2)
{
cout << "user number 2 is older than user number 1" << "\n";
}
else
{
cout << "user number 1 is older than user number 2" << "\n";
}
else
{
if (user_age_1 > 100 && user_age_2 > 100)
{
cout << "both users are over a 100 years old" << "\n";
}
}
Obviously, the second else does not have a matching if. On the other hand this:
Code:
if (User_Age_1 < User_Age_2)
{
cout << "User 2 is older than User 1.";
}
else if (User_Age_1 > User_Age_2)
{
cout << "User 1 is older than User 2.";
}
else if (User_Age_1 > 100 && User_Age_2 > 100)
{
cout << "Both users are older than 100.";
}
else if (User_Age_1 == User_Age_2)
{
cout << "Both users are the same age.";
}
is equivalent to:
Code:
if (User_Age_1 < User_Age_2)
{
cout << "User 2 is older than User 1.";
}
else
{
if (User_Age_1 > User_Age_2)
{
cout << "User 1 is older than User 2.";
}
else
{
if (User_Age_1 > 100 && User_Age_2 > 100)
{
cout << "Both users are older than 100.";
}
else
{
if (User_Age_1 == User_Age_2)
{
cout << "Both users are the same age.";
}
}
}
}
Clearly, every else has a matching if. There is an if with no else, but that is not a problem.
Originally Posted by
Ewiv
Your final statement of an if else-if block of code should always be just else.
That's not accurate, as C_Plus_Plus_96 demonstrated in post #3 and as I have elaborated on in this post.