Reputation: 270
I have an Ternary Operator in my Code and I Don't want to return any value from that Ternary operator ...
Can i write a Ternary operator with return value as void ...
Example :
int a = 10;
int b = 20;
Can i write as
(a<b ? a+=b : a-=b);
It's Showing an error like
The left-hand side of an assignment must be a variable
Thank You ...
Upvotes: 2
Views: 2555
Reputation: 234665
No, the ternary operator is itself an expression so it must evaluate to something. a += b;
is a statement to putting it in a ternary does not make grammatical sense.
Either
a += a < b ? b : -b;
or
if
, else
in the obvious way.In engineering code, (1) is quite idiomatic.
Upvotes: 4
Reputation: 22233
Can i write a Ternary operator with return value as void
No, you can't.
The thing you can do is:
a = a<b ? a+b : a-b;
Or even:
a += a<b ? b : -b;
Upvotes: 7