What Does the Unary Question Mark () Operator Do

What does the unary question mark (?) operator do?

It returns a single character string. It is the shortest way to write a single-character string literal. Use it when you want to define a lot of single-character strings. It is a heritage from Ruby <1.9, where it used to return the ASCII code for that character. I don't understand what you mean by "break the language orthogonality".

What does the question mark and the colon (?: ternary operator) mean in objective-c?

This is the C ternary operator (Objective-C is a superset of C):

label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;

is semantically equivalent to

if(inPseudoEditMode) {
label.frame = kLabelIndentedRect;
} else {
label.frame = kLabelRect;
}

The ternary with no first element (e.g. variable ?: anotherVariable) means the same as (valOrVar != 0) ? valOrVar : anotherValOrVar

What is this question mark operator about?

As you may have noticed, Rust does not have exceptions. It has panics, but their use for error-handling is discouraged (they are meant for unrecoverable errors).

In Rust, error handling uses Result. A typical example would be:

fn halves_if_even(i: i32) -> Result<i32, Error> {
if i % 2 == 0 {
Ok(i / 2)
} else {
Err(/* something */)
}
}

fn do_the_thing(i: i32) -> Result<i32, Error> {
let i = match halves_if_even(i) {
Ok(i) => i,
Err(e) => return Err(e),
};

// use `i`
}

This is great because:

  • when writing the code you cannot accidentally forget to deal with the error,
  • when reading the code you can immediately see that there is a potential for error right here.

It's less than ideal, however, in that it is very verbose. This is where the question mark operator ? comes in.

The above can be rewritten as:

fn do_the_thing(i: i32) -> Result<i32, Error> {
let i = halves_if_even(i)?;

// use `i`
}

which is much more concise.

What ? does here is equivalent to the match statement above with an addition. In short:

  1. It unpacks the Result if OK
  2. It returns the error if not, calling From::from on the error value to potentially convert it to another type.

It's a bit magic, but error handling needs some magic to cut down the boilerplate, and unlike exceptions it is immediately visible which function calls may or may not error out: those that are adorned with ?.

One example of the magic is that this also works for Option:

// Assume
// fn halves_if_even(i: i32) -> Option<i32>

fn do_the_thing(i: i32) -> Option<i32> {
let i = halves_if_even(i)?;

// use `i`
}

The ? operator, stabilized in Rust version 1.13.0 is powered by the (unstable) Try trait.

See also:

  • Is the question mark operator ? equivalent to the try! macro?
  • Why do try!() and ? not compile when used in a function that doesn't return Option or Result?

What does the question mark character ('?') mean in C++?

This is commonly referred to as the conditional operator, and when used like this:

condition ? result_if_true : result_if_false

... if the condition evaluates to true, the expression evaluates to result_if_true, otherwise it evaluates to result_if_false.

It is syntactic sugar, and in this case, it can be replaced with

int qempty()
{
if(f == r)
{
return 1;
}
else
{
return 0;
}
}

Note: Some people refer to ?: it as "the ternary operator", because it is the only ternary operator (i.e. operator that takes three arguments) in the language they are using.

What does the question mark at the end of a method name mean in Ruby?

It is a code style convention; it indicates that a method returns a boolean value (true or false) or an object to indicate a true value (or “truthy” value).

The question mark is a valid character at the end of a method name.

https://docs.ruby-lang.org/en/2.0.0/syntax/methods_rdoc.html#label-Method+Names

What does the unary operator - do on unsigned data types in C/C++ (and on different compilers)?

The relevant quote from the Standard is actually this:

(§5.3.1/8) The operand of the unary - operator shall have arithmetic or unscoped enumeration type and the result is the negation of its operand. Integral promotion is performed on integral or enumeration operands. The negative of an unsigned quantity is computed by subtracting its value from 2n, where n is the number of bits in the promoted operand. The type of the result is the type of the promoted operand.

(This is from C++11; it used to be 5.3.1/7 in older versions.)

So -num will be evaluated as 2CHAR_BIT*sizeof(num) - num (‡). The result will be of the same type as the operand (after integer promotion), i.e. it will also be unsigned.

I just tested with GCC and it seems to perform the operation in precisely the way described by the Standard. I'll assume this is the case for Visual C++ as well; otherwise it's a bug.


(‡) This formula assumes that the relevant number of bits corresponds to the size (in bits) of the variable in memory. As Keith Thompson points out in the comment, this can't be true if there are padding bits (i.e. when not all bits participate in the representation of the numerical value, which is possible according to §3.9.1/1). On a system that uses more bits to store the value than are used to represent the numerical value, the formula will not be accurate. (I, personally, am not actually aware of any such system, though.)

What does ?: do in Kotlin? (Elvis Operator)

TL;DR: If the resulting object reference [first operand] is not null, it is returned. Otherwise the value of the second operand (which may be null) is returned. Additionally, the operator can throw an exception if null is returned.


The Elvis operator is part of many programming languages, e.g. Kotlin but also Groovy or C#.
I find the Wikipedia definition pretty accurate:

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true, and otherwise evaluates and returns its second operand. It is a variant of the ternary conditional operator, ? :, found in those languages (and many others): the Elvis operator is the ternary operator with its second operand omitted.

The following is especially true for Kotlin:

Some computer programming languages have different semantics for this operator. Instead of the first operand having to result in a boolean, it must result in an object reference. If the resulting object reference is not null, it is returned. Otherwise the value of the second operand (which may be null) is returned. If the second operand is null, the operator is also able to throw an exception.

An example:

x ?: y // yields `x` if `x` is not null, `y` otherwise.
x ?: throw SomeException() // yields `x` if `x` is not null, throws SomeException otherwise

What is a Question Mark ? and Colon : Operator Used for?

This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.

Here's a good example from Wikipedia demonstrating how it works:

A traditional if-else construct in C, Java and JavaScript is written:

if (a > b) {
result = x;
} else {
result = y;
}

This can be rewritten as the following statement:

result = a > b ? x : y;

Basically it takes the form:

boolean statement ? true result : false result;

So if the boolean statement is true, you get the first part, and if it's false you get the second one.

Try these if that still doesn't make sense:

System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");

Does the unary operator really gets executed first?

The "expression" that the unary operator is applied after the evaluation of is a, not any expression it might be part of.



Related Topics



Leave a reply



Submit