我个人总是使用它们检查函数内部的值,但在我们的大学,一位老师希望我们总是检查函数外部的值。如果我们要用相同的检查值多次调用函数,我认为在函数之外检查一次值可能是个好主意。但是,如果您忘记检查临界值,它可能会给您带来错误,例如程序中的分段错误。
我已经粘贴了我正在处理的代码。在学校,我们应该检查函数之外的值,但我认为这很疯狂,在这种情况下是浪费时间。主要功能在代码的末尾,您可以在检查 malloc 的返回值(函数外的 init_unsecure 和函数内的 init_secure)或在删除元素之前检查元素是否存在时(函数外的 remove_unsecure 谁重复)时看到差异存在函数中的while循环和函数内部的remove_secure)。
你怎么看?检查函数内部的值不是很明显吗?
#include <stdlib.h>
typedef struct strens
{
int v[100];
int n;
} StrEns, *Ens;
// init struct pointer (need to check if return value is not NULL)
Ens init_unsecure()
{
Ens e;
if ((e = malloc(sizeof(StrEns))) != NULL)
e->n = 0;
return e;
}
// init struct pointer and check if malloc is not NULL
Ens init_secure()
{
Ens e;
if ((e = malloc(sizeof(StrEns))) == NULL)
exit(EXIT_FAILURE);
e->n = 0;
return e;
}
// insert element
Ens insert(Ens e, int x)
{
e->v[e->n] = x;
++e->n;
return e;
}
// return if element exists or not
int exists(Ens e, int x)
{
int i = 0;
while (i < e->n && e->v[i] != x)
++i;
return (i != e->n);
}
// remove element (need to check if element exists before)
Ens remove_unsecure(Ens e, int x)
{
--e->n;
int i = 0;
while (e->v[i] != x)
++i;
e->v[i] = e->v[e->n];
}
// remove element if exists
Ens remove_secure(Ens e, int x)
{
--e->n;
int i = 0;
while (i < e->n && e->v[i] != x)
++i;
e->v[i] = e->v[e->n];
}
// comparing init_unsecure vs init_secure && remove_unsecure vs remove_secure
int main()
{
Ens e1, e2, e3;
if ((e1 = init_unsecure()) == NULL)
return EXIT_FAILURE;
if ((e2 = init_unsecure()) == NULL)
return EXIT_FAILURE;
if ((e3 = init_unsecure()) == NULL)
return EXIT_FAILURE;
e1 = init_secure();
e2 = init_secure();
e3 = init_secure();
if (exists(e1, 42))
remove_unsecure(e1, 42);
if (exists(e2, 42))
remove_unsecure(e2, 42);
if (exists(e3, 42))
remove_unsecure(e3, 42);
remove_secure(e1, 42);
remove_secure(e2, 42);
remove_secure(e3, 42);
return EXIT_SUCCESS;
}