Nimmagadda Gowtham
Nimmagadda Gowtham

Reputation: 270

Can we write an ternary operator without a return value

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

Answers (2)

Bathsheba
Bathsheba

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

  1. write a += a < b ? b : -b;

or

  1. Use if, else in the obvious way.

In engineering code, (1) is quite idiomatic.

Upvotes: 4

BackSlash
BackSlash

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

Related Questions