gpt4 book ai didi

c++ - 我误解了 assert() 的用法吗?

转载 作者:IT老高 更新时间:2023-10-28 21:47:49 27 4
gpt4 key购买 nike

我在看the assert() reference page当我阅读给定的示例时,我被卡住了:

/* assert example */
#include <stdio.h>
#include <assert.h>

int main ()
{
FILE * datafile;
datafile=fopen ("file.dat","r");
assert (datafile);

fclose (datafile);

return 0;
}

In this example, assert is used to abort the program execution if datafile compares equal to 0, which happens when the previous call to fopen was not successful.

我完全同意如果 fopen() 失败,assert() 将中止执行。但是我担心这个例子的正确性:

在我看来,assert() 是用来检测通常不会发生的情况(比如将 NULL 指针传递给函数其文件表明这是被禁止的)。

在此示例中,无法打开文件并不是通常不会发生。事实上,我可以看到许多失败的原因。该文件不存在,程序可以在没有所需权限的情况下运行,等等。

我宁愿做这样的事情:

/* not longer an assert example */
#include <stdio.h>
#include <assert.h>

int main ()
{
FILE * datafile;
datafile=fopen ("file.dat","r");

if (datafile != NULL)
{
// Do something, whatever.
fclose (datafile);
} else
{
// Report the error somehow.
}

return 0;
}

我对 assert() 应该如何使用的理解不正确吗?


编辑和好消息!

似乎被推荐的网站是由严格的人统治的。这是我从一位网站维护者那里收到的邮件:

Hi Julien, I have to agree, the example code was poorly chosen. It has now been just rewritten to something more appropriate.

Many thanks for pointing this out, and sorry for any inconveniences this may have caused to you.

Best regards,

还有更新的例子:

/* assert example */
#include <stdio.h>
#include <assert.h>

void print_number(int* myInt) {
assert (myInt!=NULL);
printf ("%d\n",*myInt);
}

int main ()
{
int a=10;
int * b = NULL;
int * c = NULL;

b=&a;

print_number (b);
print_number (c);

return 0;
}

很高兴看到有些人在互联网上做得很好! ;)

最佳答案

先生,您说的完全正确。这是 assert 的错误用法。

关于c++ - 我误解了 assert() 的用法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3316853/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com