hdb3
hdb3

Reputation: 259

is there a non-fatal equivalent to assert in c?

I would like to write assert statement but not abort the program. So perhaps use exact same syntax as assert() but called expect(). Of course I can write my own, but assert is quite clever (e.g. it knows not only the file and line number but even the expression which is not TRUE). I could of course dig into the library and C-v/C-c a solution. But this is such an obvious generic request I can't believe there is not a good solution already. Which should of course be easily found here...

Upvotes: 2

Views: 1128

Answers (3)

hdb3
hdb3

Reputation: 259

With credit to BЈовић

#ifdef  NDEBUG
#define expect(chk) ((void *)0)
#else
#define expect(chk) (chk ? (void) (0) : fprintf(stderr,"%s:%d %s: expectation (%s) failed.\n", __FILE__ , __LINE__ , __func__ , #chk))
#endif

This version

  • writes to stderr, not stdout
  • can be disabled like assert() with the NDEBUG macro

It looks as much like the assert() message as possible, though of course it doesn't have the flexibility that assert does in terms of other parameters.

I didn't see why forcing the use of a semicolon is useful - since if there is one it works, and if there isn't it still works!

Some cleverer solution like try...catch around assert() was my hoped for answer, though!

Upvotes: 2

BЈовић
BЈовић

Reputation: 64223

No, there are no such thing. However, it is quite easy to write it as :

#define expect( chk )  \ 
    if (!(chk)) \
        printf("Assertion (%s) failed %s at line %d ", #chk, __FILE__,__LINE__);

This test :

int main()
{
  expect(0);
  expect(1);

  return 0;
}

is going to print the first failed assertion :

Assertion (0) failed t.c at line 8 

Live demo.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

It's because assert is a preprocessor macro, and so can use the __LINE__ and __FILE__ macros as the whole macro invocation is expanded into a single line.

You can easily make your own:

#define expect(value, message) \
    do \
    { \
        if (!(value)) \
        { \
            fprintf(stderr, "%s failed in %s:%d\n", #value, __FILE__, __LINE__); \
        } \
    } while(0)

Upvotes: 9

Related Questions