Use of assert instead of if

3

I was reading a book on data structures implemented in C ++ and here's the author with the following code snippet:

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

This is a code to access an element in an array at index i .

My question is:

Why did the author use assert instead of if ? the reason would be performance? In what cases would it be best to use assert instead of if ?

    
asked by anonymous 17.02.2017 / 20:03

1 answer

4

The reason even has to do with performance yes.

The assert() function can be turned on or off with a build policy. So while you are testing you leave it on, so if a programming error occurs, ie in this case someone used as an argument in the call of this function (or operator, which nonetheless is a function) a value that it could not be used .

After the application is ready, you can turn off usage and gain space and processing.

Obviously you can only turn it off if it has been very well tested and you are sure there will never be a call with wrong values. Although if this happens the maximum that will occur is the application to break, which is what assert would also do, after all it always ends the application immediately if the condition is false.

When the application can be dynamically linked (DLL for example) and you do not have control of what you are going to call your function, you usually have to leave assert .

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

So when generating the run for production itself, you can replace the assert with a code that does something other than break, can log the error and show a cute message to the user, who knows until you start over.

You have more details although it's a bit different because it's another language in What is the purpose of the "assert ()" function and when should we use it? and Is there any functionality similar to Assert (assertions) in C #? .

    
17.02.2017 / 20:23