When do we use the ASSERT function?

Asked 2 years ago, Updated 2 years ago, 98 views

There was an announcement in the OpenCV tutorial about using the alert function, so I'm curious how to use it

c c++ assert

2022-09-21 20:02

1 Answers

assert is written to terminate the program if the factor is false. It is mainly used for debugging and highlights error messages in the event of an unexpected situation

Example of use:

assert(length >= 0);
assert(length>= 0&&"length" is a negative number!");
assert("length" is a negative number!", ", length >= 0));

The main reason for debugging is that you can use the NDEBUG macro to make the alert statement not evaluation in release mode. But you shouldn't abuse it anywhere. Unexpected bugs can occur if you use the alert() without thinking. Possible scenarios are

// If released, x++ will not run
assert(x++);

// This is the right chord
assert(x);    
x++;

// Depending on how foo() is implemented, it may or may not be safe.
assert(foo());

// This is safer.
int ret = foo();
assert(ret);


2022-09-21 20:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.