Return type of '?:' (ternary conditional operator)
Expressions don't have return types, they have a type and - as it's known in the latest C++ standard - a value category.
A conditional expression can be an lvalue or an rvalue. This is its value category. (This is somewhat of a simplification, in C++11
we have lvalues, xvalues and prvalues.)
In very broad and simple terms, an lvalue refers to an object in memory and an rvalue is just a value that may not necessarily be attached to an object in memory.
An assignment expression assigns a value to an object so the thing being assigned to must be an lvalue.
For a conditional expression (?:
) to be an lvalue (again, in broad and simple terms), the second and third operands must be lvalues of the same type. This is because the type and value category of a conditional expression is determined at compile time and must be appropriate whether or not the condition is true. If one of the operands must be converted to a different type to match the other then the conditional expression cannot be an lvalue as the result of this conversion would not be an lvalue.
ISO/IEC 14882:2011 references:
3.10 [basic.lval] Lvalues and rvalues (about value categories)
5.15 [expr.cond] Conditional operator (rules for what type and value category a conditional expression has)
5.17 [expr.ass] Assignment and compound assignment operators (requirement that the l.h.s. of an assignment must be a modifiable lvalue)
How is the return type of a ternary operator determined?
This has nothing to do with how the return type is deduced and everything to do with operator precedence. When you have
std::cout << (abs(c2-c1) == abs(r2-r1)) ? 1 : 2 << std::endl;
it isn't
std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
because ?:
has lower precedence than <<
. That means what you actually have is
(std::cout << (abs(c2-c1) == abs(r2-r1))) ? 1 : (2 << std::endl);
and this is why you get an error about an <unresolved overloaded function type>
. Just use parentheses like
std::cout << ((abs(c2-c1) == abs(r2-r1)) ? 1 : 2) << std::endl;
and you'll be okay.
Why can't we have return in the ternary operator?
The ternary operator evaluates to an expression and expressions can't contain a return statement (how would that behave if you were to assign the expression to a variable?). However, you could very well return the result of a ternary operator, i.e. return condition? returnValue1 : returnValue2;
On your specific point, I don't see why you would like to return. It looks like you're trying to do something only if a condition is fulfilled. A simple if
statement would probably be more adequate there.
How do you use the ? : (conditional) operator in JavaScript?
This is a one-line shorthand for an if-else statement. It's called the conditional operator.1
Here is an example of code that could be shortened with the conditional operator:
var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}
if (userIsYoungerThan21) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}
This can be shortened with the ?:
like so:
var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");
Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:
userIsYoungerThan21 ? serveGrapeJuice() : serveWine();
They can even be chained:
serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');
Be careful, though, or you will end up with convoluted code like this:
var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;
1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.
return statement in ternary operator c++
The second and third arguments to the ternary operator are expressions, not statements.
return a
is a statement
Does Python have a ternary conditional operator?
Yes, it was added in version 2.5. The expression syntax is:
a if condition else b
First condition
is evaluated, then exactly one of either a
or b
is evaluated and returned based on the Boolean value of condition
. If condition
evaluates to True
, then a
is evaluated and returned but b
is ignored, or else when b
is evaluated and returned but a
is ignored.
This allows short-circuiting because when condition
is true only a
is evaluated and b
is not evaluated at all, but when condition
is false only b
is evaluated and a
is not evaluated at all.
For example:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Note that conditionals are an expression, not a statement. This means you can't use assignment statements or pass
or other statements within a conditional expression:
>>> pass if False else x = 3
File "<stdin>", line 1
pass if False else x = 3
^
SyntaxError: invalid syntax
You can, however, use conditional expressions to assign a variable like so:
x = a if True else b
Think of the conditional expression as switching between two values. It is very useful when you're in a 'one value or another' situation, but it doesn't do much else.
If you need to use statements, you have to use a normal if
statement instead of a conditional expression.
Keep in mind that it's frowned upon by some Pythonistas for several reasons:
- The order of the arguments is different from those of the classic
condition ? a : b
ternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, JavaScript, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the argument order). - Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
- Stylistic reasons. (Although the 'inline
if
' can be really useful, and make your script more concise, it really does complicate your code)
If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example, x = 4 if b > 8 else 9
is read aloud as x will be 4 if b is greater than 8 otherwise 9
.
Official documentation:
- Conditional expressions
- Is there an equivalent of C’s ”?:” ternary operator?
What are the side effects and return type in ternary operator in c++?
The result-type of the conditional (or ternary) operator is the common type of both branches. In your case it's int
(because char
can be implicitly be converted to int
easily, but not always the other way around). If there isn't any common type then it's an error.
You get 49
because it happens to be your systems encoded value for '1'
(ASCII).
Unexpected type resulting from the ternary operator
As the other answers have stated, this behavior is because both possible results of a ternary expression must have the same type.
Therefore, all you have to do to make your ternary version work the same way as convert1()
is to cast the int
to an Object
:
static Object convert2(double d) {
return ((d % 1) == 0) ? ((Object) (int) (d)) : d;
}
Ternary operators in JavaScript without an else
First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.
This means several things:
- use ternary expressions only when you have a variable on the left side of the
=
that is to be assigned the return value - only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
- each part of the expression (after ? and after : ) should return a value without side effects (the expression
x = true
returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)
In short - the 'correct' use of a ternary expression is
var resultofexpression = conditionasboolean ? truepart: falsepart;
Instead of your example condition ? x=true : null ;
, where you use a ternary expression to set the value of x
, you can use this:
condition && (x = true);
This is still an expression and might therefore not pass validation, so an even better approach would be
void(condition && x = true);
The last one will pass validation.
But then again, if the expected value is a boolean, just use the result of the condition expression itself
var x = (condition); // var x = (foo == "bar");
UPDATE
In relation to your sample, this is probably more appropriate:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
Related Topics
Why Do Objects of the Same Class Have Access to Each Other'S Private Data
What Are the Differences Between C-Like, Constructor, and Uniform Initialization
How to Detect Whether There Is a Specific Member Variable in Class
How Does the Import Library Work - Details
Why Are #Ifndef and #Define Used in C++ Header Files
When Do I Use a Dot, Arrow, or Double Colon to Refer to Members of a Class in C++
Rules For C++ String Literals Escape Character
Testing Pointers For Validity (C/C++)
Can Main Function Call Itself in C++
Are the Days of Passing Const Std::String & as a Parameter Over
Difference in Make_Shared and Normal Shared_Ptr in C++
How to Erase an Element from Std::Vector≪≫ by Index
What's the Difference Between Assignment Operator and Copy Constructor
Do You Use Null or 0 (Zero) For Pointers in C++
How to Write Iso C++ Standard Conformant Custom New and Delete Operators