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.
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.
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.
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.
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.
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.
Nothing will be evaluated if the assert fires, but both expressions must have the right return type, otherwise this macro will just break compilation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With