Perform an assignment and an operation using a ternary operator + && in Objective-C? - 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?)

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);
Actually, I don't know Objective-C. For all know, it might be possible!
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 ?:.

The difference you are experiencing is due to Objective-C having:
(a) true procedures (void functions/methods) which return no value; and
(b) a stronger type system than PHP
In your example the primary problem is (a) - you are calling methods which return nothing, and nothing is not a boolean value.
In PHP functions always return something, a function defined as returning void is actually defined as returning a "useless" value. However PHP will convert just about anything to anything (and does so inconsistently, for added "fun"), so a "useless" value has a boolean value - though what that is probably depends on the phase of the moon ;-) This feature does mean that you can reliably chain a "void" function after one which returns a value - <expr convertible to boolean> && <"void" function> will work in PHP (but the resulting boolean value is arbitrary). The same thing will not work in Objective-C (do not try to fix it with the comma operator, there are hidden traps with that operator).
So provided you stick with functions/methods which return either a boolean, or a type implicitly or explicitly convertible to boolean (e.g. for pointer types nil is false, other values true; for integral types 0 is false, everything else true) you can "conditionally chain" operations. Whether you should do this is a different question...
P.S. If you want to be confusing, this is short:
(isItOpen = !isItOpen) ? [it open] : [it close];
which will make most folks do a double-take ;-)

Your code would work fine as long as the close and open methods you are executing on it return boolean values. Otherwise, no cigar.

If you want to use the ternary operator, you can do like this:
isItOpen ? ([it close], isItOpen = NO) : ([it open], isItOpen = YES);
Or:
isItOpen ? [it close] : [it open];
isItOpen = !isItOpen;
But this is not a good programming style and you should avoid it.
The following code is much more readable (at least by a C/C++/Objective-C programmer):
if (isItOpen)
[it close];
else
[it open];
isItOpen = !isItOpen;
In order of preference, I recommend you use the third version of the code, then the second, then the first.

Related

What is the “and” and “or” Operator in Kotlin?

I used an || operator within the Kotlin IDEA but was throwing an error. This confused me, one of the first queries when searching google was a closed stack overflow thread with a snarky "answer" comment which wasn't helpful.
The first query in google hit is some function "or" gibberish.
My code:
if(inputAmount >= 0 || inputAmount = -99)
I understand what is "wrong". there was some logic errors the second part of the "if" statement should have been inputAmount == -99. In my case, the code needed to further be adjusted because of the actual type that was being used.
if(inputAmount >= 0.0 || inputAmount.toInt() == -99)
This appears to be different then other languages in that other languages just simply allow you to have your "logic" error with the "inputAmount = -99". So the '||' operator is allowed and is similar to most other languages.
So first step if encounter this error is to make sure your logic is correct. (check)
infix functions > sense according to the documentation "or" and "and" are infix functions that don't use the short circuit, is it technically wrong to call the "||" operator an "or" operator and should be called logical 'or'?
when referring to the infix 'or' how do people refer to that in Kotlin?
in boolean logic takes statements. A=b is a statement that is always true
No, it isn't. In C, C++ and Java it's an expression, and its value is the value of b. If b is false, it's false, if b is 10, it's 10. And you really don't want to confuse "statements" in programming languages with "statements" in logic; they are entirely different things.
Separately, C and C++ (but not Java) allow || to work on all integral types, and not just booleans (because they didn't originally have booleans as a separate type).
when referring to the infix function 'or' how do Kotlin folk typically refer to that?
Bitwise or for integral types, and I've never actually seen anyone use non-short-circuiting or on booleans, but if I had to I'd call it... well, non-short-circuiting or.
is it technically wrong to call the "||" operator an "or" operator and should be called logical 'or'
Both || and or (on booleans) are "logical 'or'" and I don't see any problem with calling them simply 'or'. If you need to distinguish use short-circuiting vs non-short-circuiting. But again, I've never actually ran into a use of the non-short-circuiting version.

Why does neither C nor Objective-C have a format specifier for Boolean values?

The app I'm working on has a credit response object with a Boolean "approved" field. I'm trying to log out this value in Objective C, but since there is no format specifier for Booleans, I have to resort to the following:
NSLog("%s", [response approved] ? #"TRUE" : #"FALSE");
While it's not possible, I would prefer to do something like the following:
NSLog("%b", [response approved]);
...where "%b" is the format specifier for a boolean value.
After doing some research, it seems the unanimous consensus is that neither C nor Objective-C has the equivalent of a "%b" specifier, and most devs end up rolling their own (something like option #1 above).
Obviously Dennis Ritchie & Co. knew what they were doing when they wrote C, and I doubt this missing format specifier was an accident. I'm curious to know the rationale behind this decision, so I can explain it to my team (who are also curious).
EDIT:
Some answers below have suggested it might be a localization issue, i.e. "TRUE" and "FALSE" are too English-specific. But wouldn't this be a dilemma that all languages face? i.e. not just C and Objective-C? Java and Ruby, among others, are able to implement "True" and "False" boolean values. Not sure why the authors of these langs didn't similarly punt on this choice.
In addition, if localization were the problem, I would expect it to affect other facets of the language as well. Take protected keywords, for instance. C uses English keywords like "include", "define", "return", "void", etc., and these keywords are arguably more difficult for non-English speakers to parse than keywords like "true" or "false".
Pure C (back to the K&R variety) doesn't actually have a boolean type, which is the fundamental reason why native printf and cousins don't have a native boolean format specifier. Expressions can evaluate to zero or nonzero integral values, which is what is interpreted in if statements as false or true, respectively in C. (Understanding this is the key to understand the semantics of the delightful !! "bang bang operator" syntax.)
(C99 did add a _Bool type, though unless you're using purest C you're unlikely to need it; derived languages and common platforms already have common boolean types or typedefs.)
The BOOL type is an ObjC construct, and -[NSString stringWithFormat:] (and NSLog) simply doesn't have an additional format specifier that does anything special with it. It certainly could (in addition to %#), and choose some reasonable string to drop in there; I don't know whether such a thing was ever considered, but it strikes me anyway as different in kind from all other format specifiers. How would you know to appropriately localize or capitalize the string representations of "yes" or "no" (or "true" or "false"?) etc? No other format specifier results in the library making decisions like that; all others are precisely numeric or insert the string result of another method call. It seems onerous, but making you choose what text you actually want in there is probably the most elegant solution.
What should the formatter display? 0 & 1? TRUE & FALSE? YES & NO? -1 and 1? What about other languages?
There's no good consistently right answer so they punted it to the app developer, for whom it'll be a clearer (and still simple) choice.
In C early days, there was no numeric printf() specifier for char, short either as there was little need for it. Now there is "%hhd" and "%hd". Any type narrower than int/unsigned was promoted.
Today, in C, _Bool type maybe printed with "%d".
#include <stdio.h>
int main(void) {
_Bool some_bool = 2;
printf("%d\n", some_bool); // prints 1 (or 0 when false)
return 0;
}
The missing link in C is its lack of a format specifier to scan into a _Bool. This leads to various solutions like the following which are not satisfactory with input like "T" or "false".
_Bool some_bool;
int temp;
scanf("%d", &temp);
some_bool = temp;

inactive ? #"inactive": #"active" syntax?

Can someone explain the inactive ? #"inactive": #"active"?
The ? : is a boolean conditional structure (wrong term) it seems but I'm not quite getting it. Don't know what it is called so can't look it up.
Seems something like:
someBooleanValue ? if it is false use what is before colon : else use
what is after
I get that it is being used to determine which string to use as the format token (in the code below). I just don't know what this ? : bit is called and what limitations/cautions/abuses there may be with it.
(and isn't ObjC like rilly hard to format in a civilized way)
UIAlertView* av = [[UIAlertView alloc] initWithTitle:#"Hey"
message:[NSString
stringWithFormat:#"While %#, I received a local notification: %#",
inactive ? #"inactive": #"active", n.alertBody]
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
This ?: thing is called a conditional operator or a ternary operator.
It's represents a simple condition
if ( CONDITION )
x = a;
else
x = b;
that can be translated to
x = CONDITION ? a : b
From that you can probably derive the functionality you're trying to accomplish/understand. Keep in mind that, although you could probably use it as a substitute to the normal if/else-if/else structure, it is considered bad programming the usage of the ternary operator out of any "assignment related action".
In the wikipedia page for it you can find a great variety of examples of the conditional operators used in different programming languages. Check this one too, the ternary operator page.
Obs: turns out that a ternary operator is not necessarily a conditional expression, but rather any operator that takes three arguments. Since for most of the programming languages the only ternary operator is the inline-if... well, that's what it's usually called.
It is called conditional operator, a kind of ternary operator (as opposed to more familiar binary a+b or unary !flag operators).
Conditional operator takes a condition, evaluates it, and returns its second or third operand depending on that result.
You can read more information here.
The use of this operator can greatly reduce code length when a lot of simple ifs are involved.
It's a ternary operator, but you have it backwards -- if the boolean is true, then do the thing before the colon, otherwise, the one after.
This is called the ternary operator and it works exactly the way you described it:
expression ? value if true : value if false;
For instance, you could use it for something like this to avoid a if - else:
int maxValue = a > b ? a : b;
Edit: #dasblinkenlight is correct, the operator you're talking about is actually called a conditional operator, which is a kind of ternary operator.

problem with an if statement

For some reason the argument I pass to my if statement is not true for even though it should be heres my code:
if (currentAttribute == cBusName)
{
NSLog(#"currentAttribute == cBusName");
}
current attribute and cBusName are both NSMutableStrings an both equal "1" but the NSLog never outputs the string in the console is there something I am missing???
The == operator is comparing that those objects are the same object (IE they point to the same address in memory), not that their values are the same.
Try
if ([currentAttribute isEqualToString: cBusName])
{
NSLog(#"currentAttribute == cBusName");
}
which compares the values of the two strings, not their location in memory.
String objects cannot be compared
using the equality (==) operator. The
reason for this is that any attempt to
perform a comparison this way will
simply compare whether the two string
objects are located at the same memory
location. Let's take a look at this
via an example:via an example:
from http://www.techotopia.com/index.php/Working_with_String_Objects_in_Objective-C, search for Comparing Strings

What advantages are there to using either AND or &&?

Currently, I'm using && and || instead of AND and OR because that's how I was taught. In most languages, however, both are valid syntax. Are there any advantages to one or the other in any language?
I did try to search for this question, but it's a bit hard. It doesn't interpret my input correctly.
You ask “Are there any advantages to one or the other in any language?” This is, of course, dependent on the programming language.
Languages that implement both and and && (and correspondingly or and ||) will do it one of two ways:
Both behave exactly the same way. In which case, there is no advantage provided by the language in using one over the other.
Each behaves differently. In which case, the advantage is that you can get different behaviour by using one or the other.
That all sounds a bit facetious, but it's really as specific as one can get without talking about a specific language. Your question explicitly wants to know about all languages, but it's a question that needs to be answered per language.
Perl has all four of {&& || and or} but they differ in their precedence. "and" and "or" have really low precedence so you can do things like "complex-function-call-here or die $!" and you won't accidentally have "or" slurp up something on its left side that you didn't want it to.
it depends on the language, but on PHP, I'd be careful about using && versus "and". The ones i often use are "&&" and "||"
http://us3.php.net/manual/en/language.operators.logical.php
$g = true && false; // $g will be assigned to (true && false) which is false
$h = true and false; // $h will be assigned to true
In some languages && will have a higher operator precedence than AND.
If both works fine, then I would say it's really personal preference, in most cases, they are compiled into same binary code like this : 11100010001000101001001010 [not real code, just an example].
&& = two keystrokes of the same key.
AND = three keystrokes of different keys.
I'm not sure what language you are using, but some languages differentiate between a normal boolean operator and a short-circuit operator. For example, the following are normal boolean operators in MATLAB:
C = or(A,B);
C = A | B; % Exactly the same as above
However, this is a short-circuit operator:
C = A || B;
The short-circuit syntax will evaluate the first argument and then, depending on the value, will potentially skip over evaluating the second argument. For example, if A is already true, B doesn't have to be evaluated for an OR operation, since the result is guaranteed to be true. This is helpful when B is replaced with a logical operation that involves some kind of expensive computation.
Here's a wikipedia link discussing short-circuit operators and their syntax for a few languages.
Unless there aren't any precedence issues, I'd say there are differences in readability. Consider the following:
if (&x == &y && &y == &z) {
// ..
}
#define AND &&
if (&x == &y AND &y == &z) {
// ..
}