-1

I always see some sort of variation of this statement:

if(!someVar)// or whatever expression
{
   someVar = new type; //or however the programmer wants to handle it
}

within code. My question is when should someone favor this method of error checking over an assert()? What are some specific examples? In my mind, assert() is probably the safer choice most of the time as you should often be asking yourself why a null or wrong value was passed to the variable in the first place. In this light then, should you ever use the if(!expr) statement?

For background I'm working specifically in C++ and with the assert.h header.

Jason
  • 2,198
  • 3
  • 23
  • 59
  • 1
    `assert()` is only enforced in debug builds and halts the program. In release builds no check is made. Therefore `assert()` is used for sanity checks but not for program logic. See: https://stackoverflow.com/questions/1571340/what-is-the-assert-function – Galik Dec 04 '16 at 18:49

2 Answers2

1

In the code sample you provided, the programmer is checking someVar, and changing it if someVar evaluates to boolean false. Within the concept of error checking, you can consider this a recoverable error (the error can be resolved by changing the value of someVar)

With an Assert, you are making the statement that someVar MUST be true, or something is wrong that you cannot recover from. Typically this is only run in debug builds, and the program will exit if the condition is false.

Erix
  • 7,059
  • 2
  • 35
  • 61
0

Well, assert will crash the program if an error occurs. However, you don't always want that. You might, for example, want to open a dialog box that tells the user about an error and gives them a chance to save their work.

A common choice for error handling is to throw an exception. Exceptions are great, because they can be caught, but if they aren't caught, they still crash the program just like an assert.

IanPudney
  • 5,941
  • 1
  • 24
  • 39