C variable assigned with return value from scope block?

I came across a code that seems invalid, but apparently this is because it has been sitting in the Mono Code Base for 2 years now . Below is a small excerpt. As a result of the macro, "mono_atomic_load_acquire" is assigned to the variable "count" in unload_data_unref (..) I assume that __tmp is what is assigned, but I can not find any information about using this method in C. Can anyone explain or give a useful link?

#define mono_atomic_load_acquire(target) ({ \ typeof (*target) __tmp = *target; \ LOAD_ACQUIRE_FENCE; \ __tmp; }) #define LOAD_ACQUIRE_FENCE MEMORY_BARRIER #define MEMORY_BARRIER mono_memory_barrier () static inline void mono_memory_barrier (void) { // platform specific code } unload_data_unref (unload_data *data) { gint32 count; do { count = mono_atomic_load_acquire (&data->refcount); g_assert (count >= 1 && count <= 2); if (count == 1) { g_free (data); return; } } while (InterlockedCompareExchange (&data->refcount, count, count - 1) != count); } 
+6
source share
2 answers

This is a GNU extension, they are called operator expressions (not to be confused with a standard C language construct called an "expression expression"). In factm, __tmp is __tmp . The docs are here.

+5
source

So this is a statement expression . This is a gcc extension and according to the documentation 6.1. Expressions and declarations in expressions :

The last in the compound expression must be an expression followed by a semicolon; the meaning of this subexpression serves as the meaning of the whole construct.

In this case, it will be __tmp . According to the documentation:

This function is especially useful when creating macro definitions "safely" (so that they evaluate each operand exactly once).

He gives this example without using statement expressions :

 #define max(a,b) ((a) > (b) ? (a) : (b)) 

compared to this safe version, with the caveat that you know the type of operands:

 #define maxint(a,b) \ ({int _a = (a), _b = (b); _a > _b ? _a : _b; }) 
0
source

Source: https://habr.com/ru/post/948486/


All Articles