C++ 什么是“断言”功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1571340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:28:18  来源:igfitidea点击:

What is the "assert" function?

c++cassert

提问by eomer

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

我一直在研究 OpenCV 教程并遇到了该assert功能;它有什么作用?

回答by Peter

assertwill terminate the program (usually with a message quoting the assert statement) if its argument turns out to be false. It's commonly used during debugging to make the program fail more obviously if an unexpected condition occurs.

assert如果它的参数结果为假,则将终止程序(通常带有引用断言语句的消息)。它通常用于调试期间,如果出现意外情况,可以使程序更明显地失败。

For example:

例如:

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

You can also add a more informative message to be displayed if it fails like so:

如果失败,您还可以添加一条信息更丰富的消息,如下所示:

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

Or else like this:

或者像这样:

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

When you're doing a release (non-debug) build, you can also remove the overhead of evaluating assertstatements by defining the NDEBUGmacro, usually with a compiler switch. The corollary of this is that your program should neverrely on the assert macro running.

当您进行发布(非调试)构建时,您还可以assert通过定义NDEBUG宏(通常使用编译器开关)来消除评估语句的开销。这样做的必然结果是您的程序永远不应该依赖于 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);

From the combination of the program calling abort() and not being guaranteed to do anything, asserts should only be used to test things that the developer has assumed rather than, for example, the user entering a number rather than a letter (which should be handled by other means).

从调用 abort() 的程序和不能保证做任何事情的组合来看,断言应该只用于测试开发人员已经假设的事情,而不是,例如,用户输入一个数字而不是一个字母(这应该是以其他方式处理)。

回答by Blake7

The assertcomputer statement is analogous to the statement make surein English.

断言计算机语句是类似于声明补充一定的英语。

回答by rahul

Take a look at

看一眼

assert() example program in C++

C++中的assert()示例程序

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.

许多编译器提供了一个 assert() 宏。assert() 宏在其参数评估为 TRUE 时返回 TRUE,如果评估为 FALSE,则执行某种操作。许多编译器会在失败的 assert() 上中止程序;其他人会抛出异常

assert() 宏的一项强大功能是,如果未定义 DEBUG,预处理器会将其折叠成任何代码。它在开发过程中是一个很大的帮助,当最终产品发布时,不会有性能损失,也不会增加程序可执行版本的大小。

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 != '
void assert(int expression);
'); /* 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

回答by Abhishek Kaushik

The assert() function can diagnose program bugs. In C, it is defined in <assert.h>, and in C++ it is defined in <cassert>. Its prototype is

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

 int x;

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

 assert(x >= 0);

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

The argument expression can be anything you want to test--a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr and aborts program execution.

参数表达式可以是您想要测试的任何内容——变量或任何 C 表达式。如果表达式的计算结果为 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

你如何使用断言()?它最常用于追踪程序错误(不同于编译错误)。错误不会阻止程序编译,但会导致程序给出错误的结果或运行不正常(例如锁定)。例如,您正在编写的财务分析程序有时可能会给出错误的答案。您怀疑问题是由变量 interest_rate 取负值引起的,这种情况永远不会发生。要检查这一点,请放置语句

assert(interest_rate >= 0); at locations in the program where interest_rate is used. If the variable ever does become negative, the assert() macro alerts you. You can then examine the relevant code to locate the cause of the problem.

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

To see how assert() works, run the sample program below. If you enter a nonzero value, the program displays the value and terminates normally. If you enter zero, the assert() macro forces abnormal program termination. The exact error message you see will depend on your compiler, but here's a typical example:

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

Assertion failed: x, file list19_3.c, line 13 Note that, in order for assert() to work, your program must be compiled in debug mode. Refer to your compiler documentation for information on enabling debug mode (as explained in a moment). When you later compile the final version in release mode, the assert() macros are disabled.

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

int dot_product(short *x, short *y, short z)
{
  int sum = 0
  int i;

  assert( ( (int)(x) & 0x3 ) == 0 );
  assert( ( (int)(y) & 0x3 ) == 0 );

  for( i = 0 ; i < z ; ++i )
    sum += x[ i ] * y[ i ];
  return sum;
}

Enter an integer value: 10

输入一个整数值:10

You entered 10.

您输入了 10。

Enter an integer value: -1

输入一个整数值:-1

Error Message: Abnormal program termination

错误信息:程序异常终止

Your error message might differ, depending on your system and compiler, but the general idea is the same.

您的错误消息可能会有所不同,具体取决于您的系统和编译器,但总体思路是相同的。

回答by stijn

Stuff like 'raises exception' and 'halts execution' might be true for most compilers, but not for all. (BTW, are there assert statements that really throw exceptions?)

诸如“引发异常”和“停止执行”之类的东西对于大多数编译器来说可能是正确的,但并非对所有编译器都是如此。(顺便说一句,是否有真正抛出异常的断言语句?)

Here's an interesting, slightly different meaning of assert used by c6x and other TI compilers: upon seeing certain assert statements, these compilers use the information in that statement to perform certain optimizations. Wicked.

这是 c6x 和其他 TI 编译器使用的 assert 的一个有趣的、略有不同的含义:在看到某些 assert 语句时,这些编译器使用该语句中的信息来执行某些优化。邪恶。

Example in C:

C 中的示例:

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

    //copy string
    while(*dest++ = *src++);
}

This tells de compiler the arrays are aligned on 32-bits boundaries, so the compiler can generate specific instructions made for that kind of alignment.

这告诉编译器数组在 32 位边界上对齐,因此编译器可以生成针对这种对齐方式的特定指令。

回答by Nnaik

There are three main reasons for using the assert() function over the normal if else and printf

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

  1. 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.

  2. 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.

  3. 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.

  1. assert() 函数主要用于调试阶段,每次你想测试一个甚至可能不会在最终代码中出现的条件时,用 printf 语句编写 if else 是很乏味的。

  2. 在大型软件部署中,断言非常方便,您可以使用在链接 assert() 函数的头文件之前定义的 NDEBUG 宏使编译器忽略断言语句。

  3. 当您设计一个函数或一些代码并想了解哪些限制代码将起作用和不起作用时,assert() 会派上用场,最后包含一个 if else 来评估它,基本上是假设。

回答by Yacoby

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:

它旨在用于测试您所做的假设。例如:

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.

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)

你想要的理想情况是你可以在你的程序中出错,比如调用一个带有无效参数的函数,并且在它出现段错误(或无法按预期工作)之前点击断言

回答by Sadikov

In addition, you can use it to check if the dynamic allocation was successful.

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

Code example:

代码示例:

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

Similar to:

相似:

##代码##