Ternary operator ?

From Remeis-Wiki
Revision as of 14:53, 12 April 2018 by Lorenz (talk | contribs) (Created page with "The ternary operator can be used to asign values to a variable depending on a condition: <pre> variable myvariable = condition ? value_if_true : value_if_false </pre> This is...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

The ternary operator can be used to asign values to a variable depending on a condition:

variable myvariable = condition ? value_if_true : value_if_false

This is equivalent to

variable myvariable;
if (condition)
  myvariable = value_if_true;
else
  myvariable = value_if_false;

As you can see, using the ternary operator results in very concise code. It communicates that one (and only one) variable is assigned and thus prevents errors like unintentionally using different variables in the two branches of the if-else-statement. However, the ternary operator might confuse people not familiar with it.


Note: There are a few cases, where the ternary operator seems to be slower than using an if condition. The reason is, so far, unknown and might be related to the underlying CPU-architecture and/or compiler, which has been used to compile S-Lang. In most cases, however, there is no difference in runtime or even a gain in speed when using the ternary operator. Especially if you run code on several machines in parallel, the ternary operator is the method of choice.

Anyway, you may use this code to check which way is faster on your machine.

variable Tif=0, Ttern=0, n, N=1000, i, iMax=1000000, b;
_for n (0, N-1)
{
  tic; _for i (0, iMax) if  (i==0) b=5; else b=7 ; Tif  +=toc;
  tic; _for i (0, iMax) b = (i==0 ?  5 :       7); Ttern+=toc;
}
vmessage("T[if] = %.2fs, T[tern] = %.2fs", Tif, Ttern);

Since the evaluation of both the if-statement and the ternary-operator is probably anyways very fast compared to your other calculations, you might also want to try this (minimally more expensive) example:

variable Tif=0, Ttern=0, n, N=1000, i, iMax=1000000, b;
_for n (0, N-1)
{
  tic; _for i (0, iMax) if  (i==0) b=sin(i); else b=cos(i) ; Tif  +=toc;
  tic; _for i (0, iMax) b = (i==0 ?  sin(i) :       cos(i)); Ttern+=toc;
}
vmessage("T[if] = %.2fs, T[tern] = %.2fs", Tif, Ttern);