Search code examples
c++guideline-support-library

Advantage of gsl assert vs assert in c++?


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;
}

Solution

  • It's not a question of performance; it's a question of flexibility.

    C assert

    This just terminates (in debug builds) if the condition is true, and usually does nothing in release builds.

    GSL contract check

    Depending on configuration, this can:

    1. Throw an exception
    2. Terminate
    3. Do nothing
      • …except signal to the optimiser that we expect the condition to hold (if supported)

    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.