Parsing macros and function arguments

1) In C, you can write a function macro like example1in the following snippet:

#define first(a, b)   a
#define second(a, b)  b

#define example1(x) splitting the tuple:  [first x] and [second x]
example1((1, 2))

which expands to splitting the tuple: [1] and [2]. This is due to the fact that the arguments deployed before the macro names firstand secondrecognized as such.

2) As an extension, you can also easily remove parentheses from an argument using variable macros:

#define unparen(...)  __VA_ARGS__
#define example2(x) removing parentheses:  unparen x
example2((1, 2))

which expands to removing parentheses: 1, 2.

3) However, the following does not work:

#define example3(x) splitting the tuple: [first(unparen x)] and [second(unparen x)]
example3((1, 2))

The cpp error is as follows:

test.c:12:16: error: macro "first" requires 2 arguments, but only 1 given
test.c:12:16: error: macro "second" requires 2 arguments, but only 1 given

first second , unparen . , -, (1). C, , ?

+4
2

, :

first second , unparen. , -, (1). C, , ?

(1), , (1), - , .

-, .

-, , , .

-, , , , , - , , - .

, , , , - , , C, .

, (3), :

  • example3

  • x *

  • first, -

  • , a first unparen (1, 2)

  • , first, unparen

... ..


* , __COUNTER__, , , x

+2

splitting the tuple: [first(unparen (1, 2))] and [second(unparen (1, 2))]

, first , unparen(1, 2)

unparen first second , , , .

+2

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


All Articles