Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What this macro return?

Tags:

c

macros

I've seen using the return value of this macro, but from the definition I can't understnad which is the value that the execution returns.

   // packet parsing state machine helpers
    #define cursor_advance(_cursor, _len) \
      ({ void *_tmp = _cursor; _cursor += _len; _tmp; })
like image 539
Maicake Avatar asked Mar 06 '26 17:03

Maicake


1 Answers

Macros don't return anything. Instead invocation of the macros are replaced inline with the body of the macro (with the macro arguments substituted).

So if you have the code

some_variable = cursor_advance(my_cursor, some_length);

then the preprocessor replaces that with

some_variable = ({ void *_tmp = my_cursor; my_cursor += some_length; _tmp; });

This in turn is an extension to the C language by the GCC C compiler called statement expression. It evaluates the statements between the ({ and }), and the result is the last expression. In the case of the example above the result is _tmp.


The whole expression

some_variable = ({ void *_tmp = my_cursor; my_cursor += some_length; _tmp; });

is equivalent to the statements

{
    void * _tmp = my_cursor;
    my_cursor += some_length;
    some_variable = _tmp;
}
like image 171
Some programmer dude Avatar answered Mar 09 '26 07:03

Some programmer dude