What is the “assert” function?

后端 未结 9 2228
耶瑟儿~
耶瑟儿~ 2020-11-27 09:16

I\'ve been studying OpenCV tutorials and came across the assert function; what does it do?

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 09:20

    It is a function that will halt program execution if the value it has evaluated is false. Usually it is surrounded by a macro so that it is not compiled into the resultant binary when compiled with release settings.

    It is designed to be used for testing the assumptions you have made. For example:

    void strcpy(char* dest, char* src){
        //pointers shouldn't be null
        assert(dest!=null);
        assert(src!=null);
    
        //copy string
        while(*dest++ = *src++);
    }
    

    The ideal you want is that you can make an error in your program, like calling a function with invalid arguments, and you hit an assert before it segfaults (or fails to work as expected)

提交回复
热议问题