WilliamKF
WilliamKF

Reputation: 43209

When should assert() be used?

In developing a large C++ programming project with many developers, we have run into issues with inappropriate use of assert() in the code which results in poor quality where the assertion does indeed occur and the product crashes.

The question is what are good principles to apply to use assert() appropriately? When is it proper to use an assert() and when is it not? Is there a list of criteria that each assertion should pass in order to be legitimate? How can we encourage proper use of assert()?

As a first crack at this, I would say that assert() should only be used to document a condition that is believed to be impossible to reach and which should be identified as an assert() failure at run time where it ever to arise because programming assumptions are being violated.

Can folks do better than this? What is your experience with assert()?

Upvotes: 13

Views: 8545

Answers (4)

MrAnonymous
MrAnonymous

Reputation: 707

I use asserts to check for any unwanted program state:

  • Function preconditions
  • Sometimes I insert them in a macro after every API call: glDrawArray(); checkOpenGLError();--checkOpenGLError() will call getGLError() if turned on
  • Data structure integrity: assert(something == null);
  • Sometimes GDB lies to me (iOS SDK 3.2). I use asserts to prove it.

Note that "unwanted program state" excludes errors that naturally occur at runtime, such as being unable to open a user-selected file due to permissions or HD failure. In these cases it is not wise to use assertions.

Upvotes: 1

seand
seand

Reputation: 5296

Much code nowadays has a lot of external dependencies and connections. I don't tend to use traditional assertions much these days, I favor exceptions. I don't feel like I can assume "this can never happen" and the checks can safely be removed in a non-debug build.

Upvotes: 0

codymanix
codymanix

Reputation: 29540

Use Exceptions for error condition which come from the outside (outside the method or outside the program) like parameter checking and missing/defective external ressources like files or connections or user input.

Use Assertions to indicate an internal defects like programming errors, conditions that shouldn't occur, e.g. class/method invariants and invalid program state.

Upvotes: 14

ggarber
ggarber

Reputation: 8360

You should use assert to check all conditions that should never happen:

  • Preconditions on input parameters
  • Results of intermediate calculations
  • Postconditions on object state

But you should include those asserts only in debug builds or when explicitly activated for release (not in builds released to the customers).

Upvotes: 1

Related Questions