An if
Expression
A common use case for an if
statement is to assign a value to a variable depending on a condition.
The following if
expression will perform the same operation by returning a value based on a condition.
The code above is a perfect scenario for the use of the ternary operator
.
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.
Using the Preprocessor
If we dare to, we can take the previous code and apply the use of preprocessor macro.
Here is the preprocessor macro definitions used above.
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.
The C++ code above may be written as a variation of the IFF
preprocessor macro.
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.
Afterthoughts
- Someone might misinterpret the
return
statement inside the IFF macro which returns only from the enclosing block. - Yes, the
END_IFF
is noise and would most probably at times be left out possibly because, intuitively, the closing curly bracket marks the end of the block. - If the lambda is not optimized then performance will suffer specially if it appears in performance critical sections.