I came across this code recently, which doesn't look legal to me (but gcc compiles it). I don't so much mind the construction as want a name for it:
#define MAX(a,b) \
({ \
typeof(a) _a = (a); \
typeof(b) _b = (b); \
(_a > _b) ? (_a) : (_b); \
})
Apparently, the last statement's value is being returned as the "value" of the expression bounded by the namespace.
Edit: Thanks for the answers guys. Turns out this is an extension to plain C called Statement Expressions.
A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string.
You cannot do that in Ruby. The return keyword always returns from the method or lambda in the current context. In blocks, it will return from the method in which the closure was defined. It cannot be made to return from the calling method or lambda.
This block is used to return control from a Shared Module to the application (or Shared Module) that called it.
Example. return (value or variable); return 10; return a; return a+b; The value will be passed back to the function where it was called. We can receive the value and do the further programming from that point.
It is not a namespace, it is a macro which returns maximum of two values.\
at the end of the statements is use to append multiple statements and create a multi-line macro.
The code is not standard C++ but it compiles in gcc because it is supported as an gcc compiler extension.
Good Read:
Statement Expressions:
A compound statement is a sequence of statements enclosed by braces. In GNU C, a compound statement inside parentheses may appear as an expression in what is called a Statement expression
.
.--------------.
V |
>>-(--{----statement--;-+--}--)--------------------------------><
The value of a statement expression is the value of the last simple expression to appear in the entire construct. If the last statement is not an expression, then the construct is of type void and has no value.
Note: This excerpt is taken from IBM XL C/C++ v7.0 documentation.
This is called a statement expression, and is a non-standard extension of GCC. It allows you to use a compound statement as an expression, with a value given by the last expression in the compound statement.
It's used here to avoid the problem that function-like macros may evaluate their arguments multiple times, giving unexpected behaviour if those evaluations have side-effects. The macro is carefully written to evaluate a
and b
exactly once.
In C++, you should never need to do anything like this - use function templates instead:
template <typename T> T max(T const & a, T const & b) {
return a > b ? a : b;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With