A function like macros that return a value

Recently I came across the following examples that return the __ret register, but without the return statement

#define READWORD(offset) ({ \ unsigned short __ret=0;\ __ret = readw(offset);\ __ret; \ }) 

Google, however, found that a function like macros could return a value. Is it possible to assume that the last statement "_ret" is equivalent to returning a value? What if I have another expression after "_ret" that changes the value of __ret. Which one will be returned?

+4
source share
2 answers

This GCC extension is called Expression Expressions .

You can use it if you do not need to be portable for compilers other than GCC (and Clang / LLVM).

+8
source

Let it break. For example, see what READWORD (1) does. The preprocessor inserts this: ({unsigned short __ret = 0; __ret = readw (1); __ret;})

Now we can see what it is for. We simply call the readw function with parameter (1) and assign it an unsigned short. After that, we only have the __ret line; Although the perfectly correct statement does not seem to do anything. But read on!

After the finals, everything goes beyond.

But embedding () matters. Elegantly, this is all an expression that has a __ret value. That way you can set it to varaible. This makes everything remarkably stable in macro arguments.

Does this get rid of?

+3
source

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


All Articles