Is it possible to make the ?: operator process several statements like in the example below?
condition ? FirstTrueExpression SecondTrueExpression : FirstFalseExpression SecondFalseExpression
And is there a way to avoid specifying the 'else' statement?
condition ? TrueExpression
You can use comma operator , to concatenate multiple expressions.
The expressions are evaluated from left to right and its resulting type and value will be ones of the righthand expression.
condition ? FirstTrueExpression, SecondTrueExpression : (FirstFalseExpression, SecondFalseExpression)
Note that you need () around (FirstFalseExpression, SecondFalseExpression) due to the operator precedence while you don't need () around FirstTrueExpression, SecondTrueExpression.
You can use
condition && TrueExpression
instead of
condition ? TrueExpression
This is thanks to short-circuit evaluation of logical and && operator:
When condition is false, condition && TrueExpression will be false (0) regardless of the value of TrueExpression, and therefore TrueExpression isn't evaluated.
When condition is true, TrueExpression is evaluated because it is needed to determine the value of condition && TrueExpression.
Related
This SSIS case expression looks perfectly valid to me, but it's coming up red. Can anybody explain why?
[Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2"
Probably because you don't have the " : {ELSE} " part of the expression. What do you want the value to be if the column does not equal "MEDICAL"?
Referring to the Microsoft Documentation, ? conditional syntax is like the following:
boolean_expression?expression1:expression2
"If the Boolean expression evaluates to TRUE, then the first expression is evaluated and the result is the expression result. If the Boolean expression evaluates to FALSE then the second expression is evaluated and its result is the expression result." Read more
so i think you are missing the second part of the expression, i might be something like this:
[Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2" : ""
Also it is better to add a NULL checking to your expression using ISNULL() function (to avoid a null value exception):
ISNULL([Copy of "final_benefit_type_grouper"])? "" : ( [Copy of "final_benefit_type_grouper"] == "MEDICAL" ? "2" : "")
It is also to follow this Link to Read more about write a case statment using a SSIS expression
I am developing an application using AngularJS. I have used the if-else conditions and ternary Operator. Once I found a code {{ !$last && ', ' || '.'}} to put the , after each entry and . at the end. It is working fine, but I have a confusion about its working process. Is it working like an if-else condition or ternary operator? My whole example is as below.
<span data-ng-repeat="allSuppliers in vm.allIncentiveSuppliers | unique:'supplierName'">
{{allSuppliers.supplierName }}{{ !$last && ', ' || '.'}}
</span>
It is a form of ternary operator. && returns first operand if it is a falsy value and second operand if first operand is truthy e.g. 1 && 3 will return 3 but 0 && 3 will return 0. Second operator is not evaluated if first is falsy. || is similar but returns first operand if it is truthy and second operand if first is falsy.
So basically cond && val1 || val2 is equivalend to cond ? val1 : val2 under condition that val1 is truthy value. If this is not the case e.g. cond && 0 || 1 this will always return last value 1 in this case.
For readability reasons you should always prefer ternary opreator ?: than boolean shortcircuting operators.
Be wary that this won't work in languages where && only return a boolean value, like C and PHP. There, 3 && 4 returns 1/true, so your code won't work as expected.
In JS, && returns the first truthy value or false. So 3 && 4 returns 3 and your code works fine.
Another thing to be careful of is when you want &&'s right-hand-side to be falsy:
cond() && false || true will always return true.
A ternary operator is basically a shorthand for if-else condition. So the syntax you provided can be termed as both.
Other varients of that expression can be:
{{ !$last ? ', ' : '.'}}
Or
{{ $last ? '.' : ','}}
I have used ternary operator before for a condition like if-else but here it's different i.e. not checking a condition before ?.
printf( "%d\n",10?0?5:11:12 );
Edited:
So,how will it evaluate 11 as by compiler because i don't see any condition before first ?.
The expression 10 ? 0 ? 5 : 11 : 12 is parsed this way: 10 ? (0 ? 5 : 11) : 12. So this means that in the first test, since 10 is true, it will evaluate 0 ? 5 : 11, which evaluates to 11 since 0 is false.
It will be solved in this manner
printf("%d\n",10?0?5:11:12);
i.e 10?(0?5:11):12
First solve 0?5:11 as 0 means false so it will return 11.
Now Condition will be like 10?11:12
As 10 is non zero condition will be true, so it will return 11.
printf( "%d\n",10?0?5:11:12 ); is of syntax (condition)?TRUE:FALSE
There are two ternary operators. For better readibility and understanding, let's put it this way
(10 ? (0 ? 5 : 11) : 12)
So, the inner condition, (0 ? 5 : 11) checks whether 0 is TRUE or FALSE. It is a FALSE value, [yes, zero is considered as FALSE and non-zero value is considered as TRUE and both are perfectly valid sysntax for conditional check]. so , it evaluates to 11.
Now, for the outer condition, the code appears as (10 ? 11 : 12). Following simmilar logic, 10 being a TRUE, it returns 11. which is passed to printf(). That's how you get your output.
Your expression is parsed as 10?(0?5:11):12 and the inner conditional expression (0?5:11) is constant folded to 11 then the entire expression is constant folded to 11 (since 10 is true since non-zero).
Notice that a condition (such as the first test operand of a ?: ternary conditional expression) can be any scalar, non-void, expression. In particular 11 is a valid condition.
What is going on is in pseudo code a little bit:
(But in the ternary operator first the inner ternary condition get's "calculated")
if (10) { //true
if(0) { //false
print 5
} else {
print 11 //Output 11
}
} else {
print 12
}
Or as a ternary operator but a little bit more readable:
(10 ? (0 ? 5 : 11) : 12)
I'm using Postgres' native array type, and trying to find the records where the ID is not in the array recipient IDs.
I can find where they are IN:
SELECT COUNT(*) FROM messages WHERE (3 = ANY (recipient_ids))
But this doesn't work:
SELECT COUNT(*) FROM messages WHERE (3 != ANY (recipient_ids))
SELECT COUNT(*) FROM messages WHERE (3 = NOT ANY (recipient_ids))
What's the right way to test for this condition?
SELECT COUNT(*) FROM "messages" WHERE NOT (3 = ANY (recipient_ids))
You can always negate WHERE (condition) with WHERE NOT (condition)
You could turn it around a bit and say "3 is not equal to all the IDs":
where 3 != all (recipient_ids)
From the fine manual:
9.21.4. ALL (array)
expression operator ALL (array expression)
The right-hand side is a parenthesized expression, which must yield an array value. The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ALL is "true" if all comparisons yield true (including the case where the array has zero elements). The result is "false" if any false result is found.
Beware of NULLs
Both ALL:
(some_value != ALL(some_array))
And ANY:
NOT (some_value = ANY(some_array))
Would work as long as some_array is not null. If the array might be null, then you must account for it with coalesce(), e.g.
(some_value != ALL(coalesce(some_array, array[]::int[])))
Or
NOT (some_value = ANY(coalesce(some_array, array[]::int[])))
From the docs:
If the array expression yields a null array, the result of ANY will be null
If the array expression yields a null array, the result of ALL will be null
Augmenting the ALL/ANY Answers
I prefer all solutions that use all or any to achieve the result, appreciating the additional notes (e.g. about NULLs). As another augementation, here is a way to think about those operators.
You can think about them as short-circuit operators:
all(array) goes through all the values in the array, comparing each to the reference value using the provided operator. As soon as a comparison yields false, the process ends with false, otherwise true. (Comparable to short-circuit logical and.)
any(array) goes through all the values in the array, comparing each to the reference value using the provided operator. As soon as a comparison yields true, the process ends with true, otherwise false. (Comparable to short-circuit logical or.)
This is why 3 <> any('{1,2,3}') does not yield the desired result: The process compares 3 with 1 for inequality, which is true, and immediately returns true. A single value in the array different from 3 is enough to make the entire condition true. The 3 in the last array position is prob. never used.
3 <> all('{1,2,3}') on the other hand makes sure all values are not equal 3. It will run through all comparisons that yield true up to an element that yields false (the last in this case), to return false as the overall result. This is what the OP wants.
an update:
as of postgres 9.3,
you can use NOT in tandem with the #> (contains operator) to achieve this as well.
IE.
SELECT COUNT(*) FROM "messages" WHERE NOT recipient_ids #> ARRAY[3];
not (3 = any(recipient_ids))?
Note that the ANY/ALL operators will not work with array indexes. If indexes are in mind:
SELECT COUNT(*) FROM "messages" WHERE 3 && recipient_ids
and the negative:
SELECT COUNT(*) FROM "messages" WHERE NOT (3 && recipient_ids)
An index can then be created like:
CREATE INDEX recipient_ids_idx on tableName USING GIN(recipient_ids)
Use the following query
select id from Example where NOT (id = ANY ('{1, 2}'))
we got if(expression) {...} for example. We all know if expression is true, it will execute lines in braces. But what is "True" in C?
Is that != 0 means true as I think?
Thank you
Here is what the standard has to say.
§6.8.4 Selection statements
Syntax
selection-statement:
if ( expression ) statement
if ( expression ) statement else statement
switch ( expression ) statement
§6.8.4.1 The if statement
Constraints
The controlling expression of an if statement shall have scalar type.
Semantics
In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0. If the first substatement is reached via a label, the second substatement is not executed.
An else is associated with the lexically nearest preceding if that is allowed by the
syntax.
Any none-zero result tests as true.
Yes, true is not-null in C and C++.