0

I've read through a lot of code where they have if statements, i've noticed other languages use this to. Asp being one. Tried googling but couldn't find a answer for it.

What exactly does ?: stand for and when to use it.

As far as I'm aware ? is equal to if() and : being equal to }else{.

Bankzilla
  • 2,086
  • 3
  • 25
  • 52
  • Is it `?:` your are looking for, or `bool ? true : false`. Because `?:` would lead to something like `value1 ?: value2` using `value1` if it evaluates to true. – steveoh Mar 15 '12 at 23:24
  • possible duplicate of [What is ?: in PHP 5.3?](http://stackoverflow.com/questions/2153180/what-is-in-php-5-3) – mario Mar 15 '12 at 23:47
  • And http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php – mario Mar 15 '12 at 23:48

7 Answers7

7

It is the ternary operator (although in most languages it is better-named as the "conditional operator").

People will often erroneously refer to it as "shorthand if/else". But this is a misnomer; if/else is a statement, ?: is an expression. In most languages, these are distinct concepts, with different semantics.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

This is called ternary operator.

It is meant to simplify code in some cases. Consider this:

var str;

if(some_condition)
  str = 'yes';
else
  str = 'no';

This can be easily rewritten as

var str = some_condition ? 'yes' : 'no';
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

Your assumption is right.

It is a Ternary operation (Wikipedia)

Daan Timmer
  • 14,771
  • 6
  • 34
  • 66
1

Essentially, the syntax is condition ? then-expession : else-expression. Typically it is used in assigning variables:

varname = something == 123 ? "yes" : "no";

But it can be used pretty much anywhere in place of a value. It's mostly useful for avoiding repetitive code:

if( something == 123) {
    varname = "yes";
}
else {
    varname = "no";
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

In Java, it's an if/else relationship.

An example of a ternary operation:

boolean bool = (x==1) ? true : false;

http://en.wikipedia.org/wiki/Ternary_operation

Justin
  • 4,196
  • 4
  • 24
  • 48
0

You could read the documentation. The section you're looking for is titled "Ternary Operator".

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
0

You can express calculations that might otherwise require an if-else construction more concisely by using the conditional operator. For example, the following code uses first an if statement and then a conditional operator to check for a possible division-by-zero error before calculating the sin function.

    if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;
    s = x != 0.0 ? Math.Sin(x)/x : 1.0;

from http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.90).aspx

DotNetUser
  • 6,494
  • 1
  • 25
  • 27