In GNU C, an expression is also formed by enclosing a compound statement in parentheses. He allows you to use loops, jumps, and local variables within an expression.
A compound statement is a set of statements enclosed in braces {}. In the structure of the expression that contains the statement, enclose the curly braces in parentheses (), for example:
({int y = foo (); int z;
if (y > 0) z = y;
else z =-y;
Z })
is a valid expression that calculates the absolute value of the Foo () function return.
In the above compound statement, the last sentence must be a semicolon-terminated expression. This expression represents the value of the entire structure. If you use a different statement in the last sentence of the curly braces, the return type of the entire structure is void, that is, there is no valid return value.
This feature makes the macro definition more secure (because each operand is evaluated only once, such as the + + operation). For example, calculating the maximum value is usually defined as such a macro in the C language:
#define MAX (A,b) ((a) > (b)? (a): (b))
However, A and B may be computed two times, and if the operands have side effects, the result will be incorrect. In GNU C, if you know the type of operand (assuming int), you can define macros in such a safe way:
#define MAXINT (a,b) \
({int _a = (a), _b = (b); _a > _b _a: _b;})
A statement is embedded in a constant expression (such as an enumeration type) and is not allowed in bit-field size or static variable initialization. If you do not know the type of operand, you can also use typeof to get the type.
Statement expressions are not supported inline in g++, and future support is unclear (they are fully supported or discarded at some point, or as a bug). For now, statement-inline expressions do not work well by default.
In addition, there are a number of semantic problems with statement-inline expressions in C + +. If you want to replace inline functions with statement-inline expressions in C + + (inline function), the destructor of the object may surprise you. For example:
#define FOO (a) ({int b = (a); B + 3;})
is not equal to
inline int foo (int a) {int b = A; return B + 3;}
Specifically, when an expression passed to Foo introduces the generation of temporary objects, the destructors for these temporary objects are used in macros earlier than the function.
It is not a good idea to use statement inline expressions in the. h header file for C + + code. Some versions of the GNU C Library use the header file of statement inline expressions to cause such bugs.
Article Source: http://nathanxu.blog.51cto.com/50836/6027