Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ assert: the precedence of the expression in an assert macro

In C++:

  assert(  std::is_same<int , int>::value  ); // does not compile

  assert( (std::is_same<int , int>::value) ); // compiles

Can anyone explain why?

like image 208
igbgotiz Avatar asked Jul 17 '14 01:07

igbgotiz


People also ask

What is assert macro in C?

C library macro - assert() The C library macro void assert(int expression) allows diagnostic information to be written to the standard error file. In other words, it can be used to add diagnostics in your C program.

How does assert () work?

The assert() function tests the condition parameter. If it is false, it prints a message to standard error, using the string parameter to describe the failed condition. It then sets the variable _assert_exit to one and executes the exit statement. The exit statement jumps to the END rule.

Is assert a macro?

The assert macro prints a diagnostic message when expression evaluates to false (0) and calls abort to stop program execution. No action is taken if expression is true (nonzero). The diagnostic message includes the failed expression, the name of the source file and line number where the assertion failed.

Why is assert a macro?

By making assert a macro instead, you can eliminate the calculation entirely when assertions are turned off. Apple's swift tackles this problem of having to resolve arguments before calling the function a bit but they don't have a precompiler, after all.


1 Answers

assert is a preprocessor macro. Preprocessor macros are dumb; they don't understand templates. The preprocessor sees 10 tokens within the parentheses:

assert( std :: is_same < int , int > :: value );

It splits at the comma. It doesn't know that this is the wrong place to split at, because it doesn't understand that std::is_same<int and int>::value aren't valid C++ expressions.

The preprocessor is smart enough to not break up the contents of inner pairs of parentheses across multiple arguments. That's why adding the extra parentheses fixes the problem.

like image 184
Brian Bi Avatar answered Sep 28 '22 09:09

Brian Bi