I can't seem to figure out how to get these if statements to work properly. I'm at the point where I just want to see how to do this properly so I can learn from it. If anyone is able to figure it out, THANK YOU.
The area that wont work is the MAX portion of it. Trying to figure out which words in the string have the most chars. Thanks again!
You are mixing if statements with conditional operators:
1 2
if (isMax(word[max].length(), word[i].length()) ? max = max : max = i)
++i;
What you are trying to do is this:
1 2 3 4 5
if ( !isMax(word[max].length(), word[i].length() ) //if isMax returns false
{
max = i;
i++;
}
As to your mixing, here's an illustration of how the two compare:
1 2 3 4 5 6 7 8 9 10 11
if (somechar == 'a')
{
//somechar is 'a'
}
else
{
//somechar is not 'a'
}
// the above is the same as:
(somechar == 'a') ? /*somechar is 'a'*/ : /*somechar is not 'a'*/ ;
They both do the same in this case, but you can't mix them up.
Your suggestion solved my problem 100%. I guess this means I will have to do some reading on the differences between if else statements and conditional operators.
Is it because "else" is not equivalent to "false" in a boolean statement that is checking for truth?
They are different things performing the same task to a certain extent.
The conditional operator was created because common statements like this:
1 2 3 4 5 6 7 8 9 10 11 12 13
int number;
bool number_even = false;
std::string statement;
if (name_empty == false)
{
statement = "number is odd";
}
else
{
statement = "number is even";
}
This can be written with the help of the conditional operator in one line, making it much shorter:
1 2 3 4 5
int number;
bool number_even = false;
std::string statement;
statement = (number_even == false) ? "number is odd" : "number is even";
As a general rule of thumb., only use the conditional operator to do these kinds of variable initialisations that depend on an expression (like number_even = false). For executing other code, especially multiple statements, always use if/else.
The conditional operator is a good tool - when it's used correctly, when used incorrectly it can really make a mess of your code. Never nest conditional operators or you'll end up in a syntax-jungle.
So conditional operators ( ? : ) and the if/else control structure can be used to do the same thing in some cases, but never mixed. When in doubt, use if/else.
Okay I see, so the conditional operator was created in order to save time and screen real estate when writing if-else's that have only one statement each. That makes sense and again, I really appreciate your detailed response and suggestions. I have incorporated you suggestions in my code, and it has really cleaned things up!