我一直在学习OpenCV教程,遇到了assert函数;它能做什么?


当前回答

assert()函数可以诊断程序错误。在C语言中,它定义在<assert.h>中,在c++中定义在<cassert>中。它的原型是

void assert(int expression);

参数表达式可以是您想要测试的任何东西——变量或任何C表达式。如果expression的值为TRUE, assert()不执行任何操作。如果表达式的计算值为FALSE, assert()在stderr上显示错误消息并中止程序执行。

How do you use assert()? It is most frequently used to track down program bugs (which are distinct from compilation errors). A bug doesn't prevent a program from compiling, but it causes it to give incorrect results or to run improperly (locking up, for example). For instance, a financial-analysis program you're writing might occasionally give incorrect answers. You suspect that the problem is caused by the variable interest_rate taking on a negative value, which should never happen. To check this, place the statement

断言(利率>= 0); 在程序中使用interest_rate的位置。如果变量变成负数,assert()宏会提醒您。然后,您可以检查相关代码以定位问题的原因。

要查看assert()如何工作,请运行下面的示例程序。如果输入非零值,程序将显示该值并正常终止。如果输入0,assert()宏强制异常终止程序。你看到的确切错误消息将取决于你的编译器,但这里有一个典型的例子:

断言失败:x,文件list19_3.c,第13行 注意,为了使assert()工作,您的程序必须在调试模式下编译。有关启用调试模式的信息,请参阅编译器文档(稍后解释)。稍后在发布模式下编译最终版本时,assert()宏将被禁用。

 int x;

 printf("\nEnter an integer value: ");
 scanf("%d", &x);

 assert(x >= 0);

 printf("You entered %d.\n", x);
 return(0);

输入整型值:10

您输入了10。

输入整型值:-1

错误信息: 程序异常终止

您的错误消息可能不同,这取决于您的系统和编译器,但总体思想是相同的。

其他回答

看一看

assert() c++示例程序

Many compilers offer an assert() macro. The assert() macro returns TRUE if its parameter evaluates TRUE and takes some kind of action if it evaluates FALSE. Many compilers will abort the program on an assert() that fails; others will throw an exception One powerful feature of the assert() macro is that the preprocessor collapses it into no code at all if DEBUG is not defined. It is a great help during development, and when the final product ships there is no performance penalty nor increase in the size of the executable version of the program.

Eg

#include <stdio.h>
#include <assert.h>

void analyze (char *, int);

int main(void)
{
   char *string = "ABC";
   int length = 3;

   analyze(string, length);
   printf("The string %s is not null or empty, "
          "and has length %d \n", string, length);
}

void analyze(char *string, int length)
{
   assert(string != NULL);     /* cannot be NULL */
   assert(*string != '\0');    /* cannot be empty */
   assert(length > 0);         /* must be positive */
}

/****************  Output should be similar to  ******************
The string ABC is not null or empty, and has length 3

此外,您还可以使用它来检查动态分配是否成功。

代码示例:

int ** p;
p = new int * [5];      // Dynamic array (size 5) of pointers to int
for (int i = 0; i < 5; ++i) {
    p[i] = new int[3]; // Each i(ptr) is now pointing to a dynamic
                       // array (size 3) of actual int values
}

assert (p);            // Check the dynamic allocation.

类似于:

if (p == NULL) {
    cout << "dynamic allocation failed" << endl;
    exit(1);
}

assert()函数可以诊断程序错误。在C语言中,它定义在<assert.h>中,在c++中定义在<cassert>中。它的原型是

void assert(int expression);

参数表达式可以是您想要测试的任何东西——变量或任何C表达式。如果expression的值为TRUE, assert()不执行任何操作。如果表达式的计算值为FALSE, assert()在stderr上显示错误消息并中止程序执行。

How do you use assert()? It is most frequently used to track down program bugs (which are distinct from compilation errors). A bug doesn't prevent a program from compiling, but it causes it to give incorrect results or to run improperly (locking up, for example). For instance, a financial-analysis program you're writing might occasionally give incorrect answers. You suspect that the problem is caused by the variable interest_rate taking on a negative value, which should never happen. To check this, place the statement

断言(利率>= 0); 在程序中使用interest_rate的位置。如果变量变成负数,assert()宏会提醒您。然后,您可以检查相关代码以定位问题的原因。

要查看assert()如何工作,请运行下面的示例程序。如果输入非零值,程序将显示该值并正常终止。如果输入0,assert()宏强制异常终止程序。你看到的确切错误消息将取决于你的编译器,但这里有一个典型的例子:

断言失败:x,文件list19_3.c,第13行 注意,为了使assert()工作,您的程序必须在调试模式下编译。有关启用调试模式的信息,请参阅编译器文档(稍后解释)。稍后在发布模式下编译最终版本时,assert()宏将被禁用。

 int x;

 printf("\nEnter an integer value: ");
 scanf("%d", &x);

 assert(x >= 0);

 printf("You entered %d.\n", x);
 return(0);

输入整型值:10

您输入了10。

输入整型值:-1

错误信息: 程序异常终止

您的错误消息可能不同,这取决于您的系统和编译器,但总体思想是相同的。

如果Assert的参数为假,Assert将终止程序(通常使用引用Assert语句的消息)。它通常在调试期间使用,以使程序在发生意外情况时更明显地失败。

例如:

assert(length >= 0);  // die if length is negative.

你也可以添加一个信息更丰富的消息显示,如果它失败了,如下所示:

assert(length >= 0 && "Whoops, length can't possibly be negative! (didn't we just check 10 lines ago?) Tell jsmith");

或者像这样:

assert(("Length can't possibly be negative! Tell jsmith", length >= 0));

在进行发布(非调试)构建时,还可以通过定义NDEBUG宏(通常带有编译器开关)来消除求值assert语句的开销。这样做的必然结果是,您的程序永远不应该依赖assert宏运行。

// BAD
assert(x++);

// GOOD
assert(x);    
x++;

// Watch out! Depends on the function:
assert(foo());

// Here's a safer way:
int ret = foo();
assert(ret);

由于程序调用abort()并且不能保证执行任何操作,因此断言应该只用于测试开发人员假设的事情,而不是用于测试用户输入的数字而不是字母(这应该通过其他方式处理)。

使用assert()函数而不是普通的if else和printf有三个主要原因

assert() function is mainly used in the debugging phase, it is tedious to write if else with a printf statement everytime you want to test a condition which might not even make its way in the final code. In large software deployments , assert comes very handy where you can make the compiler ignore the assert statements using the NDEBUG macro defined before linking the header file for assert() function. assert() comes handy when you are designing a function or some code and want to get an idea as to what limits the code will and not work and finally include an if else for evaluating it basically playing with assumptions.