[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: abort vs. assert

From: Jim Meyering
Subject: Re: abort vs. assert
Date: Mon, 15 Mar 2010 21:36:17 +0100

Bruno Haible wrote:

> Jim Meyering wrote:
>> These days, I prefer to use assert(e) over "if (!e) abort();".
>> We used to have to avoid using assert due to portability issues,
>> but those went away many years ago.
> I disagree. The reason why I never use 'assert(e)' is to make sure
> the safety checks are actually present.
> There are two kinds of assertions:
> 1) Assertions at the entry of some function or module.
>    Here, the purpose of 'if (!e) abort();' in production code is to
>    limit the effects of buggy code or invalid data that comes into
>    _our_ modules but originated outside our modules. If invalid data
>    is present, I prefer it to be caught before it enters my module,
>    than to have complaints that my module produced wrong output.
> 2) Assertions in the middle or at the end of some function.
>    Here, when someone uses 'assert', it may happen that deployed, supposedly
>    "production quality" code runs into bugs that the developer thought he
>    had guarded against. But the guard was defined away by someone who compiled
>    with -DNDEBUG.
>    It is ironic: in the development environment, where consequences
>    of buggy code would be minor, we want to have safety checks. But
>    in production code, where the consequences of bugs can be major,
>    some people want to be able to remove the safety checks? And when
>    the bug then hits, of course, the responsibility is with us, the
>    developers!

If you expect assertions to be disabled, or are willing to cater
to the needs of those who do that, then I can see why you would
prefer code that won't be removed by the preprocessor.

However, I'm sure you realize it needn't be called "assert".
You might just as well define and use your own macro,

    #define ASSERT(e) do { if (!(e)) abort (); } while (0)

That would not risk being incidentally disabled, and lends itself
to more readable uses -- for one, you assert a condition rather than
testing its negation.  This may seem a trivial point, but it can help
when asserting more complicated expressions.

In addition, if you really don't want the bug reports from people
who disable assertions, you could still use "assert", but add code
like this in a few strategic places:

    #ifdef NDEBUG
    # error "disable assertions herein at your peril -- and if you disable then 
nonetheless, then don't report bugs"

reply via email to

[Prev in Thread] Current Thread [Next in Thread]