Short Question : Conditional Operator

Hi guys ^^ just a short question regarding conditional operators.

for example, i have:

(condition)? (if true) : (else);

How do i make my (else) void or useless?
Use a value that won't affect the operation
eg:
1
2
3
int a = 2 * ( condition ? 5 : 1 );
int b = 2 + ( condition ? 5 : 0 );
std::string s = (std::string)"hello" + ( condition ? " world" : "" );
Last edited on
I can't find any reference to the employment of the trinary operator in the way you are proposing so believe you should not use it in this way... especially as it would be confusing to other programmers.
Where exactly did you look? That's a fairly common use of the trinary operator.
The best and simplest way i could think of was this..
 
(a==b) ? a*b : a=a;


just wondering if there is any simpler alternatives to this?
Last edited on
How did you gauge that that way is the "best"? As Bazzy's post suggested, the actual shape of the subexpression would depend on the whole expression.
If the expression was, for example, a=(a==b) ? a*b : a=a;, that would indeed work, but what if it was c=(a==b) ? a*b : a=a;?
Also note that the else operand could be simply replaced by a. You did know that the assignment operator returns the value of the left operand after assingment, right? (x=a)==a
Last edited on
Thanks helios, i just replace the else operand with an a xD that solves everything lol =)
Topic archived. No new replies allowed.