Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation for assert macro

Tags:

c++

I couldn't comment on the answer itself, so: about Using comma to prevent the need for brace pair

 #define MY_ASSERT(expr) ((expr) || (debugbreak(), 0))

Here debugbreak() returns void, but we still wish to have 0 as an rvalue.

How does (debugbreak(), 0) work to return 0? I understand that the return value of debugbreak() is discarded and 0 is returned, but debugbreak generates an exception, so how can anything be evaluated afterward? I suppose my question can be generalised to any similar binary operator where the first part being evaluated exits the program.

like image 958
user490735 Avatar asked Feb 28 '11 06:02

user490735


People also ask

What is the purpose of assert 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.

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.

Why is assert used?

The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False, check the example below.

What is assert in programming?

An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.


2 Answers

It's a type system hack.

#define MY_ASSERT(expr) ((expr) || (debugbreak(), 0))
//   note the or operator here  ^

The || operator takes two bool-typed (or convertible) expressions. debugbreak() is void-typed. To make it bool, use the following rule:

(FOO, BAR)
//    ^  determines the type of the entire comma expression

This is the same as {FOO; BAR} except that a block (in braces) has no type.

like image 166
Fred Foo Avatar answered Nov 08 '22 23:11

Fred Foo


Nothing will be evaluated if the assert fires, but both expressions must have the right return type, otherwise this macro will just break compilation.

like image 37
sharptooth Avatar answered Nov 09 '22 00:11

sharptooth