Given the the below two statements, could someone help me use only the ternary operator instead of if statements?
I have tried a lot to do that:
if(strstr(cv[i],a.c_str()))
{
o=1;
p=cv[i];
p=p.substr(a.size()+1);
}
else o+=4;
if (b^*s && c++ + 1 ^ *s)
{
cout << b;
if (b^--c)
cout << (c - b>1 ? "-" : ",") << c;
if (a)
cout << ",";
b = c = *s;
}
The ternary operator is an expression, which returns a value when evaluated:
<result> = <condition> ? <when true> : <when false>
In this pseudo code
<when true>
and<when false>
must also be an expression. Although you can pack several statements into a single expression with some trick (e.g. to embrace it with ado { <statements> } while(false);
structure), the ternary operator is not meant to be used for this. You should use a ternary operator when both thethen
and theelse
branches are consisted of a single statement, and optionally you may use the return value of the expression.So to take a very simple example, instead of writing
It is cleaner and simpler to use a ternary operator:
However it is not the case when the conditional branches contain multiple statements, as in that case the use of a ternary operator would just make your code look more confusing and harder to understand.