Getting too many arguments provided by the macro function when compiling errors when defining lambda inside assert (assert.h) in Xcode [C ++]

I am using the assertion macro from assert.h I have defined a lambda to perform assertion validation.

int val1 = 0; int val2 = 1; const auto check = [val1,val2]()-> bool { return val1 < val2; }; // no error for this call assert(check() && "Test is failed"); // no error for this call assert([=]()-> bool { return val1 < val2; }() && "Test is failed"); 
 //compile error for this call "too many arguments provided to function-like macro invocation" assert([val1,val2]()-> bool { return val1 < val2; }() && "Test is failed"); 

why am i getting

too many arguments provided to functionally matched macro invocation

to compile an error for the case when I use the assert macro and define a lambda with more than one argument in the capture list?

+5
source share
2 answers

The problem is the comma in the capture list.

The preprocessor has an extremely limited understanding of C ++ syntax; it basically performs trivial text replacement. If the comma is not between the matching inner brackets (and not the token part, like a string literal, of course), the preprocessor will consider it as a separator of the macro arguments.

So, the preprocessor thinks that you are calling assert with two arguments [this and the rest of the record behind the first comma, which gives an error.

You can fix this error using an extra set of parentheses:

 int i = -7, j = 7; assert(([i,j](){return i + j;}())); 

For standard lovers:

The sequence of preprocessing tokens limited by external sliding brackets makes a list of arguments for the macro function. The individual arguments in the list are separated by a comma in the preprocessing notes, but the preprocessing tokens are separated by comma between the matching inner brackets. If the argument list contains sequences of preprocessing tokens that otherwise act as preprocessor directives 155, the behavior is undefined.

16.3 / 11 in N4140, the emphasis is mine.

+5
source

The preprocessor is very simple; it sees all commas as argument delimiters.

Thus, you cannot use a macro if you pass something with a comma as a macro argument.

+2
source

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


All Articles