I know the use of assert
in C++. Wanted to know is there any difference between and any benefit(I think assert
is costlier according as mentioned in https://www.learncpp.com/cpp-tutorial/7-12a-assert-and-static_assert/ so performance wise, are both same?) in using gsl_assert
over assert
? Why gsl_assert
was added in gsl library since there is already assert
support in c++(even though assert
came from 'C', since we add #include<cassert>
for using assert
in C++)?
#include <iostream>
#include <gsl/gsl_assert>
using namespace std;
int main()
{
int val;
cin >> val;
Ensures( val > 5 );
return 0;
}
assert in C. Assert is a macro that is used to check specific conditions at runtime (when a program is under execution) and is very useful while debugging a program. To use it, you must include the header file "assert.h" in the program. The expression can be any valid C language expression many a time it is a condition.
Good placement of asserts can reduce chances of exceptions by catching out-of-bounds accesses, invalid pointer dereferences, invalid state machine transitions, and nonsensical operations (like a malloc of 12MB on a 64kB MCU).
Following is the declaration for assert () Macro. expression − This can be a variable or any C expression. If expression evaluates to TRUE, assert () does nothing. If expression evaluates to FALSE, assert () displays an error message on stderr (standard error stream to display error messages and diagnostics) and aborts program execution.
Despite the numerous benefits, the practice of using asserts in firmware is not common or agreed upon. By using asserts proactively in embedded systems on debug and production builds, developers can both prevent more bugs before shipping and quickly surface and fix them after shipping.
It's not a question of performance; it's a question of flexibility.
This just terminates (in debug builds) if the condition is true, and usually does nothing in release builds.
Depending on configuration, this can:
In some configuration modes, I suppose GSL's Expects
and Ensures
macros end up doing pretty much the same thing as assert
. But not in all.
It's worth noting, though, that the GSL behaviour appears not to be dependent on build configuration (debug vs release). I guess (and I am only guessing) that, for performance-critical code, a sensible project maintainer would choose mode #1 or #2 in debug builds, and #3 (or possibly #2) in release builds.
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