http://qs321.pair.com?node_id=460838


in reply to Trinary Operator Semantics

I just compiled your code on a VAX (VMS) both with and without optimization enabled. In each case, both routines generated identical code.

To me, the ternary operator is most useful when used in a function call argument list or other complex expression where one element needs to change based on some condition. These become much easier and concise to express with a ternary operator than with two separate statements within an if/else construct.

Contrived example:

printf("File name: %s\n", (ptr == NULL) ? "<unspecified>" : ptr);

...or...

char *s; if (ptr == NULL) s = "<unspecified>"; else s = ptr; printf("File name: %s\n", s);

What it boils down to is that the ternary operator presents an expression and can be used anywhere an expression can be used. if/else is a (compound) statement and is much more restrictive about where it can be used.

# trinary movl %eax, -28(%ebp) # to_return # ifelse movl $1, -28(%ebp) # to_return
The trinary function is handling the variable between registers, whereas ifelse is using a memory location. This is another boost to the trinary operator.

Doesn't the $1 notation mean that the value 1 is encoded in the instruction itself (immediate value)? You seem to imply that it is referencing a variable somewhere else in memory.

90% of every Perl application is already written.
dragonchild

Replies are listed 'Best First'.
Re^2: Trinary Operator Semantics
by hardburn (Abbot) on May 26, 2005 at 19:46 UTC

    Doesn't the $1 notation mean that the value 1 is encoded in the instruction itself (immediate value)?

    You are correct. My ASM is rusty.

    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.