Use of assert instead of if

Asked

Viewed 234 times

4

I was reading a book about data structures implemented in C++ and here the author presents the following code snippet:

T& operator[](int i) {
    assert(i >= 0 && i < length);
    return a[i];
  }

It is a code to access an element in a array in the index i.

My question is:

Why did the author use assert instead of if? the reason would be for performance? In which cases it would be better to use assert instead of if?

  • 1

    http://stackoverflow.com/a/1571360/6809703

  • 1

    Asserts are used to debug how your function behaves and to look for flaws in the execution of the code, an if is a control to change the flow of your program.

1 answer

6


The reason even has to do with performance yes.

The function assert() can be switched on or off with a compiler directive. So while testing you leave it on, so if there is a programming error, ie in this case someone used as argument in the call of this function (or operator, which is not a function) a value that it could not be used.

Once the application is ready you can turn off the use and gain space and processing.

Obviously you can only turn it off if you have been very well tested and there is no doubt that there will never be a call with wrong values. Although if that happens the most that will occur is the application break, which is what the assert() would also, after all it always ends the application immediately if the condition is false.

When the application can be linked dynamically (DLL for example) and one does not have control of what will call its function usually has to let the assert().

The use of assert() is also interesting because you can replace it with a more powerful version or do something specific you need.

So when generating the execution for production itself, you can replace the assert() by a code that does something other than break, can log in error and show a cute message to the user, who knows until start again.

It has more details despite being a little different because it is another language in What is the purpose of the "assert()" function and when to use it? and Is there any functionality similar to Assert (affirmations) in C#?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.