ani
ani

Reputation: 39

Assert Keyword in C

Other than the textbook definitions of the keyword 'assert' What is the actual use case ?

Its not a commonly used keyword so examples are rare to find explaining the actual implementation and its use in Code

Upvotes: 2

Views: 184

Answers (1)

ncarrier
ncarrier

Reputation: 475

You can use it in any way you may find suitable. Personally, I use it for writing simple unit tests when I don't want to rely on any dependency.

Some people use it for checking pre and post-conditions, like for example:

int foo(int a, int b) {
    int result;

    assert(a > 0 && a < 150);
    assert(b > 20 && b < 1000);

    // do something with a, b and store something in result

    assert(result > -10 && result < 10);

    return result;
}

But please beware that assertions can be disabled at compile time by defining the NDEBUG macro. So for example if you rely on it for pre-conditions, you may want to double them with tests built un-conditionally.

Upvotes: 4

Related Questions