Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform an assignment and an operation using a ternary operator + && in Objective-C?

In the name of ternary bliss (and for a disdain of the verbose)... I am hoping, and am somewhat surprised that....

BOOL isItOpen = YES;
isItOpen = (isItOpen ? YES : NO); // yes, dumbie, it's open.

works fine… but that…

isItOpen = (isItOpen ? [it close] && NO : [it open] && YES);

results in Invalid operands to binary expression ('void' and 'int')

I can't seem to track down a simple yes or no as to whether one can conditionally chain operations with && (or ||), like one does in say, BASH or PHP. I tried various combinations of & and && arrangements, to no avail.. as I am a C idiot... but if this "way of doing it" is NOT possible, linguistically… is there another - that is as concise? (ie, no ifs involed?)

like image 279
Alex Gray Avatar asked Dec 12 '25 01:12

Alex Gray


1 Answers

The C (and by extension, C++ and Objective-C1) operators form expressions; they're designed to evaluate to a value, rather than control program flow.

So whilst ?:, && and || all offer short-circuit evaluation of their arguments, you can't use them to conditionally call arbitrary functions;2 you should use traditional control-flow constructs (i.e. if) for that.

You could use the little-known comma operator to achieve this, but I strongly recommend that you don't, because it's highly unidiomatic, and difficult to read. e.g.:

isItOpen = condition ? (func1(), NO) : (func2(), YES);


  1. Actually, I don't know Objective-C. For all know, it might be possible!
  2. And by "arbitrary", I mean functions that return void, or a type that's not implicitly convertible to bool in the case of && and ||, or a non-matching type in the case of ?:.
like image 173
Oliver Charlesworth Avatar answered Dec 15 '25 16:12

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!