rmaicle

Programming is an endless loop; it's either you break or exit.

Licensed under a Creative Commons Attribution-ShareAlike 4.0 International License (CC BY-SA).
You are free to copy, reproduce, distribute, display, and make adaptations but you must provide proper attribution. Visit https://creativecommons.org/ or send an email to info@creativecommons.org for more information about the License.

An if Expression

Date: 2015-12-12 13:45:13 +0000

A common use case for an if statement is to assign a value to a variable depending on a condition.

int a = 0;
if (some_condition) {
    a = 1;
} else {
    a = 2;
}

The following if expression will perform the same operation by returning a value based on a condition.

int a = if (some_condition) {
    return 1;
} else {
    return 2;
}

The code above is a perfect scenario for the use of the ternary operator.

int a = ? (some_condition) : 1 : 2;

Using the ternary operator with multiple statements could make the syntax a bit messy. With C++11, the goal could be achieved using a lambda but with a bit of clutter too.

int a = [=] {
    if (some_condition) {
        return 1;
    } else {
        return 2;
    }
}();

Using the Preprocessor

If we dare to, we can take the previous code and apply the use of preprocessor macro.

int a = [=] { if (some_condition) {         int a = IFF (some_condition) {
        return 1;                               return 1;
    } else {                                } else {
        return 2;                               return 2;
    }                                       }
}();                                        END_IFF

Here is the preprocessor macro definitions used above.

#define IFF(C)      [=] { if (!!(C))
#efine END_IFF      }();

Variation One

When the return values are already known beforehand but some code needs to be executed depending on the condition. The following C++ code shows the scenario.

int a = 0;
if (some_condition) {
    a = 1;
    // ... other code whe condition is true
} else {
    a = 2;
    // ... other code whe condition is false
}

The C++ code above may be written as a variation of the IFF preprocessor macro.

int a = IFF (some_condition, 1, 2) {
    // code when condition is true
} else {
    // code when condition is false
} END_IFF

Line 1 tells us that when some_condition evaluates to true, it will return the first argument. Otherwise, the second argument is returned.

An implementation of the preprocessor macros.

#define IFF(C, RT, RF)                      \
[=] {                                       \
        bool b = !!(C);                     \
        decltype(RT) whenTrue = RT;         \
        decltype(RF) whenFalse = RF;        \
        if (b)

#define END_IFF                             \
        return b ? whenTrue : whenFalse;    \
}();

Afterthoughts

  •  thoughts