c - 如何使变量返回 N/A? (c语言)

标签 c

<分区>

我有一个 C 语言的代码,我有一个返回 int 值的函数。但是,如果条件不完整,我需要该函数的一个变量来给我 N/A 值(不是它在开始时初始化的大数字)。任何提示如何做到这一点?非常感谢...

最佳答案

C中没有N/A,最接近它的是值指针。您可以让一个函数返回一个指向 int 的指针,并在未满足条件的情况下返回 NULL。

基本上有两种可能性,返回一个指向静态存储的指针,或者一个指向用 malloc 分配的存储的指针。

int *may_fail_static(int input) {
    static int result;
    if (input == 42)
         return NULL;
    else {
        result = 3 * input;
        return &result;
    }        
}

int *may_fail_malloc(int input) {
    int *result;
    if (input == 42)
        return NULL;
    else {
        result = malloc(sizeof *result);
        if (result == NULL) {
            fprintf(stderr, "Out of memory!\n");
            exit(1);
        }
        *result = 3 * input;
        return result;
    }
}

两者都有缺点:静态版本不可重入(不是线程安全的)。 malloc 版本有很大的分配开销,客户端必须在使用后显式释放存储空间。

这就是为什么在 C 中,您通常会找到这种类型的函数:

/* Returns 0 on success, or -1 on failure */
int may_fail(int input, int *result) {
    if (input == 42)
        return -1;
    else {
        *result = 3 * input;
        return 0;
    }
}

客户可以通过以下方式使用它:

int x;
if (may_fail(42, &x) == -1) {
    fprintf(stderr, "ERROR: may_fail failed!\n");
    exit(1);
}
/* Answer value is now stored in x. Go ahead */

关于c - 如何使变量返回 N/A? (c语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19756458/

相关文章:

c - 断点如何在嵌入式设备上工作?

c - perlxstut 中应该有 newSVuv 而不是 newSVnv 吗?

c - GTK+ 线程与 OpenGL 的 GLUT/FreeGLUT

c - 显示当前正在执行的 C 代码行

c - 如何在win32中设置UI控件的Tab顺序?

c++ - 如何获取具有 FILE* 的文件名?

c - 我是否需要在 for 循环中使用 strcat 检查目标字符串长度

c - 在 Objective-C 中包装 C 库的技巧

c++ - 对常规文件进行 Epoll

c - setwaitedtimer函数不调用c中的回调函数