Does the shorthand ternary operator make multiple calculations? - ternary-operator

The ternary operator has a shorthand version, i.e.
var = exp ?: exp2
I know it works in PHP. Other languages may have also picked it up. C# has similar functionality (for the context of this question) - ??.
When the condition passes, is the expression evaluated again, or is the result stored somewhere?

http://msdn.microsoft.com/en-us/library/ms173224.aspx
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
It is stored, not computed twice.

Related

Comparison of Ternary operator, Elvis operator, safe Navigation Operator and logical OR operators

Comparison with Ternary operator vs Elvis operator vs safe Navigation Operator vs logical or operators in angular
Ternary Operator(statement ? obj : obj)
let gender = user.male ? "male" : "female";
Elvis Operator (?: )
let displayName = user.name ?: "";
Safe Navigation Operator (?.)
let displayName = user.name ?. "";
Logical or operators
let displayName = user.name || "";
The above all operators are similarly doing the same process. What are the difference benefits and which one is best & worst?
Maybe I've missed a couple versions, but to my knowledge, TypeScript does not have an elvis operator or a safe navigation operator. The only extra thing they have is a non-null assertion operator !., but this is only for the compiler, and in the compiled js the ! will be removed. Angular however, does have the safe navigation operator inside their templates, but under the hood this will resolve into a logical or ||. The benefit here is increased readability and smaller templates.
Besides that, TypeScript does have the ?: notation, but this is used in interfaces or method parameters to indicate that the value is optional
Which leaves us with the ternary operator vs logical or. You would use the first one if there are 3 values. The question, the answer yes result, and the answer no result to said question.
And the latter when there are 2 values. Where the first one, if resolved to truthy will be the answer, and otherwise the second one, regardless of its value.
Benefit wise, I can't really say much. I would expect them to be equally fast, with a marginal difference. Perhaps readability is increased with the ternary option, which you obviously can always use instead of the logical or ||, but personally I like to use the ||, because it keeps the code compact.
TLDR;
Ternary Operator
Simplified if else, available everywhere
Elvis operator ?:
Not available in typescript/javascript/angular and essentially the same as ||
Safe navigation operator ?.
Only available in angular templating, used to prevent null pointers in object parameter navigation
Logical or ||
If not left hand, then right hand. Even more simplified if else. Available in typescript/javascript/angular
let gender = user.male ? "male" : "female";
can Used in javascript(Typescript) as well as in HTML tag binding ,
Basically when you use this operator in javascript code it means if first statment is true than execute first otherwise execute second option
In angular2 Terms Ternary Operatoris known as Safe Navigation Operator (?.) or you can use the term Elvis Operator (?: ) which is used at the time of fetching asynchronous data from the backend or some kind of databse.
alternate :- you can also use Elvis Operator (?: ) in angular2 template like this (we can say this is shorthand property)
let gender = user.gender || "";
Have a look here too
Replacement of Elvis Operator of Angular2 in Typescript
Safe Navigation Operator (?.) which is also wrongly called Elvis operator in Angular2 only
this is an Angular2 template binding thing, it's not available in javascript.
Ternary Operator(statement ? obj : obj)
This when you want to check for a condition and if that condition is truthy, return a value or if it's falsy return another value.
Logical or operators
This when you want to return a value based on it's own existence or truthiness (so there is no other rule involved), it's very different from Ternery.
let displayName = user.name || "";
In above example, you're saying if either of those expression are truthy, return it, where is in bellow :
let gender = user.male ? "male" : "female";
What you're saying is : if my condition is truthy , return "male" otherwise return "female"
Elvis Operator (?: )
This is NOT available in javascript and you could find it in other languages like PHP and it's basiacly the same as Ternery operator, but simplified , in a case where the left side of the comparison ( the truth side ) can be used as the returned value :
so :
let m = something ?: somethingElse // if in case of truthiness of `something` you want to return `something` , you can do this
is equal to :
let m = something ? something : somethingElse
EDIt :
It doesn't make sense to compare them, they're not doing the same thing at all.
#Milad RameshRajendran you can use the term elvis instead of Safe Navigation Operator (?.) in angular2, according to me both are same don't confuse with name
I got something from this source:
Elvis Operator (?: )
The "Elvis operator" is a shortening
of Java's ternary operator. One
instance of where this is handy is for
returning a 'sensible default' value
if an expression resolves to false or
null. A simple example might look like
this:
def gender = user.male ? "male" : "female" //traditional ternary operator usage
def displayName = user.name ?: "Anonymous" //more compact Elvis operator
Safe Navigation Operator (?.)
The Safe Navigation operator is used
to avoid a NullPointerException.
Typically when you have a reference to
an object you might need to verify
that it is not null before accessing
methods or properties of the object.
To avoid this, the safe navigation
operator will simply return null
instead of throwing an exception, like
so:
def user = User.find( "admin" ) //this might be null if 'admin' does not exist
def streetName = user?.address?.street //streetName will be null if user or user.address is null - no NPE thrown
But I want to know the above all operators are similarly doing the same process. What are the difference benefits and which one is best & worst?

What's the difference among Expression,Statements and Declaration from the view of compiler?

I am going through the Go source code of ast.go at here,and there are 3 types of interfaces that are Expression,Statement and Declaration. But only with the source code I couldn't figure out the difference between them.What I could figure out is that expression results in a object that could be assigned or compared or used as parameter,while statements are some flow control like if-else or for loop.
But I found some definitions like
// An IncDecStmt node represents an increment or decrement statement.
IncDecStmt struct {
X Expr
TokPos token.Pos // position of Tok
Tok token.Token // INC or DEC
}
shouldn't it be a expression?I feel confused how to distinguish expressions and statements,are there any rules?
The Golang spec uses those terms:
Expressions: specifies the computation of a value by applying operators and functions to operands.
Statements: control execution
Declarations (and scope): binds a non-blank identifier to a constant, type, variable, function, label, or package
The IncDecStmt is specified as
IncDecStmt = Expression ( "++" | "--" ) .
The "++" and "--" statements increment or decrement their operands by the untyped constant 1.
It uses an expression, but remains a statement (don't produce a new value).
Those are common terms in CS. An expression produces a value while a statement often doesn't (this last point depends of the language, in fact, some languages consider expressions as a subcategory of statements).
From Wikipedia :
In most languages, statements contrast with expressions in that
statements do not return results and are executed solely for their
side effects, while expressions always return a result and often do
not have side effects at all.
In Go an expression may be used as statement.
Your confusion seems to come from the increment and decrement operators. In Go, contrary to most C-based languages, the increment and decrement statements don't produce a value, they're statements and not expressions. That is, you may not write
b := a++

?: in Objective C [duplicate]

This question already has an answer here:
Is this ternary conditional ?: correct (Objective) C syntax?
4 answers
In this iOS tutorial, there is a line of code with a ? followed by a :. In the context of the comment for the code, I thought it was some sort of ternary operation, however, that's obviously not the syntax for a ternary operator. Is there a name for what is happening in this code with the ?:?
// Initialize the list of weather items if it doesn't exist
NSMutableArray *array = self.xmlWeather[#"weather"] ?: [NSMutableArray array];
It's a GCC extension:
6.7 Conditionals with Omitted Operands
The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.
Therefore, the expression
x ? : y
has the value of x if that is nonzero; otherwise, the value of y.
This example is perfectly equivalent to
x ? x : y
In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.

Limit operator (if variable>value then variable=value)

Is there such a thing as a Limit operator that lets you control the maximum or minium value of a variable.
if variable > value then variable = value
My question is not language specific, but answers in different languages are appreciated (esp. Delhpi).
I know operators differ from language to language, but mostly in syntax.
Would an operator like this be usefull enough?
Some languages have "min" operator that can be used for this: variable = min(variable, limit)
Basically, an operator is nothing else than a function.
Unary operators like ! (not) can be mapped with the function
Boolean not(Boolean)
Binary operators like + (plus) can be mapped with the function
Integer plus(Integer, Integer)
...
So, you can define any missing "operator" on your own as a function. Many languages don't allow to define operators on your own. In Groovy you can overload existing operators:
http://groovy.codehaus.org/Operator+Overloading

Exclamation operator?

I'm learning D and have seen a lot of code like this:
ushort x = to!ushort(args[1]);
I assume this casts args[1] to ushort, but what's the difference between this and cast(ushort)?
EDIT: And what other uses does the exclamation mark operator have?
In D,
to!ushort(args[1])
is shorthand for the template instantiation
to!(ushort)(args[1])
and is similar to
to<ushort>(args[1])
in languages like C++/Java/C#.
The exclamation point is to note the fact that it's not a regular argument, but a template argument.
The notation does not use angle brackets because those are ridiculously difficult to parse correctly for a compiler (they make the grammar very context-sensitive), which makes it that much more difficult to implement a correct compiler. See here for more info.
The only other use I know about is just the unary 'not' operation (e.g. false == !true)... I can't think of any other uses at the moment.
Regarding the cast:
cast(ushort) is an unchecked cast, so it won't throw an exception if the value is out of range.
to!ushort() is a checked cast, so it throws an exception if the value is out of range.
The exclamation mark here is not an operator, it is just a token part of the explicit template instantiation syntax (described in detail here).
std.conv.to (docs) is a function template for converting between arbitrary types. It is implemented entirely in the library and has no special support in the language. It has a broader and different scope compared to the cast operator.
The to template takes two type parameters; a "to" type and a "from" type, in that order. In your example, the template is explicitly instantiated with the single type argument ushort for the "to" parameter, and a second type argument string (assuming args comes from the first parameter to main) is automatically inferred from the regular function argument passed to the function (args[1]) as the "from" parameter.
The resulting function takes a string parameter and returns a ushort parsed from that string, or throws an exception if it failed. The cast operator will not attempt this kind of high-level conversion.
Note that if there is more than one explicit template parameter, or that parameter has more than one token in it (ushort is a single keyword token), you must wrap the template parameter list in parentheses:
ushort result;
result = to!(typeof(result))(args[1]);
In this example, typeof, (, result and ) are four separate tokens and the parentheses are thus required.
To answer your last question, the ! token is also used for the unary not operator, unrelated to template instantiations:
bool yes = true;
bool no = !yes; // 'no' is false
You already got two excellent answers by jA_cOp and Merhdad. I just want answer directly to the OP question (what's the difference between this and cast(ushort)?) - The difference is that cast(ushort)args[1] will not work (you cannot cast from a string to an uint just like that), while the to!(type)(param) template knows what to do with the string and how to convert it to the primitive type.

Resources