You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中用&&检查函数指针是否为NULL并调用函数

问题:使用&&检查函数指针NULL并调用时编译报错

我的测试代码:

#include <stdio.h>

typedef unsigned char  u8,  * pu8;
typedef unsigned short u16, * pu16;
typedef unsigned       u32, * pu32;

void sum(int a, int b) {
    printf("%d\n", a + b);
}
/*
void temp_fun1(void (*fn) (int, int)) {
    fn && fn(1, 2);
}*/

void temp_fun2(int * num) {
    num && (*num)++;
}

int main(void) {
    int a = 6;
    
    temp_fun2(&a);
    printf("%d\n", a);
    temp_fun2(NULL);
    printf("%d\n", a);
    
    // temp_fun1(sum);
    // temp_fun1(NULL);

    return 0;
}

正如预期,temp_fun2函数运行正常,但temp_fun1函数触发编译错误:

./main.c:12:8: error: invalid operands to binary expression ('void (*)(int, int)' and 'void')
    fn && fn(1, 2);
    ~~ ^  ~~~~~~~~
1 error generated.

我尝试了fn && (*fn)(1, 2);的写法,依然报错,该如何解决?


问题原因

C语言中,逻辑与运算符&&要求两个操作数都必须是可转换为布尔值的表达式,但返回void类型的函数调用表达式没有值,无法参与逻辑运算。而temp_fun2中的(*num)++是int类型的表达式(返回自增前的数值),所以可以正常参与&&运算。

解决办法

1. 最清晰的标准写法:使用if判断

这是可读性最高、最符合C编程规范的写法,完全避免语法问题:

void temp_fun1(void (*fn) (int, int)) {
    if (fn) {
        fn(1, 2);
    }
}

2. 单行逻辑运算符写法(利用逗号表达式)

如果一定要用单行的形式,可以通过逗号运算符将void调用包装成合法的表达式,逗号表达式的结果取最后一个操作数的值,这里用1作为占位的有效数值:

void temp_fun1(void (*fn) (int, int)) {
    fn && (fn(1, 2), 1);
}

这样&&的右操作数是一个int类型的表达式,符合语法要求,同时fn(1,2)会被正常执行(当fn非NULL时)。


内容的提问来源于stack exchange,提问作者csh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:31:13