Geas MUD, enter the Aventure!
Geas Home | Play the Game

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ] The ?: expression

This is a very condensed way of writing an if/else statement and return a value depending on how the test turned out. This isn't a statement naturally, it's an expression since it returns a value, but it was hard to explain earlier before explaining the if/else statement.

Suppose you want to write the following:

if (test_expression)
    var = if_expression;
    var = else_expression;

You can write that much more condensed in this way:

var = test_expression ? if_expression : else_expression;
    name = day == 2 ? "tuesday" : "another day";

It can be debated if writing code this way makes you code easier or harder to read. As a rule it can be argued rather successfully that one expression of that kind does make it clearer, but that a combination of several only makes it worse. Something like this definitely isn't an improvement:

name = day == 2 ? time == 18 ? "miller time" : "tuesday" : "another day";

This document was generated by Ronny Wikh on July, 8 2003 using texi2html