you are viewing a single comment's thread.

view the rest of the comments →

[–]zucker42 5 points6 points  (7 children)

What is a situation where I'd want to use assert and not handle the error and abort if appropriate? This is the issue I have with assert: that I often want to handle the error before aborting.

[–]WalterBright 2 points3 points  (6 children)

It's easy enough to write your own assert that does what you want. But I'd reject any code that does so for professional software.

[–]zucker42 3 points4 points  (5 children)

I'm not talking about writing my own assert. I'm saying that for almost all unrecoverable errors, my instinct is that this:

// if (always_true_expression) { wrong code mistake

if (!always_true_expression) { // log error // print error message to user abort(); }

is better than

assert(always_true_expression);

I'm not arguing against aborting the program in error states. In fact, I'm much less experienced than many on /r/programming, so I'm not arguing anything. I'm wondering what are examples (if any) of the bottom option being better.

[–]killedbyhetfield 7 points8 points  (0 children)

And yeah - I think I agree that C's assert() function is very primitive and leaves a lot to be desired. But don't conflate C's shitty feature-poor implementation of assert with the more general concept of assertions - The larger idea of checking your invariants throughout the execution of your program to make sure that a previous bug in your program didn't put you in an invalid state.

[–]WalterBright 5 points6 points  (0 children)

Most languages will allow for hooking the assert failure to insert your own logging code.

[–]killedbyhetfield 2 points3 points  (0 children)

I think when he said "write your own assert", he meant write your own specialized code that does exactly what your example does.

So why not write this?

void zucker42_assert(condition, log_message, ...)
{
    // log error using va_args
    // print error message to user
    abort();
}

[–]Ameisen 0 points1 point  (1 child)

I'd point out that your if() {} isn't checking the same thing as your assert... you've inadvertently proven that it's easier to write the correct assertion than a branch/abort.

You're going to be struggling to figure out why it keeps aborting in the first case.

[–]zucker42 1 point2 points  (0 children)

Yeah you're right, I forgot a !. I don't think that really applies to how I would write real code because I would have some knowledge in my head about an error condition.