Python None 类型的 C 等效项

标签 c nonetype

是否有与 Python None 类型等效的 C 数据类型?

我试图在互联网上搜索它,但我找不到任何东西。

谢谢,

最佳答案

Python 是动态类型的,因此您可以将变量名称绑定(bind)到任何类型,例如字符串、数字或 NoneType。由于 C 是静态类型,变量锁定为特定类型,但是没有什么可以阻止您创建可以是任何类型的类型。

例如,带有标记字段的 union 来指示类型,如下面的完整程序。首先,标签和 union 类型允许您存储和选择任何类型:

enum uberType { ETYP_NONE, ETYP_INT, ETYP_DOUBLE, ETYP_CHARPTR };
typedef struct {
    enum uberType type;
    union { int valInt; double valDouble; char *valCharPtr; };
} tUberType;

然后使用一些辅助函数将 uber-type 设置为特定类型的值:

void makeNone(tUberType *ut) {
    ut->type = ETYP_NONE;
}

void makeInt(tUberType *ut, int val) {
    ut->type = ETYP_INT;
    ut->valInt = val;
}

void makeDouble(tUberType *ut, double val) {
    ut->type = ETYP_DOUBLE;
    ut->valDouble = val;
    }

void makeCharPtr(tUberType *ut, char *val) {
    ut->type = ETYP_CHARPTR;
    ut->valCharPtr = val;
}

最后,一个测试工具,包括一个输出函数:

#include <stdio.h>

void evalUber(tUberType *ut, char *post) {
    switch (ut->type) {
    case ETYP_NONE:
        printf("none:%s", post);
        break;
    case ETYP_INT:
        printf("int:%d%s", ut->valInt, post);
        break;
    case ETYP_DOUBLE:
        printf("double:%f%s", ut->valDouble, post);
        break;
    case ETYP_CHARPTR:
        printf("charptr:%s%s", ut->valCharPtr, post);
        break;
    default:
        printf("?%s", post);
        break;
    }
}

int main(void) {
    tUberType x;
    makeNone(&x); evalUber(&x, "\n");
    makeInt(&x, 42); evalUber(&x, "\n");
    makeDouble(&x, 3.14159); evalUber(&x, "\n");

    return 0;
}

测试工具main的输出如预期的那样:

none:
int:42
double:3.141590

关于Python None 类型的 C 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62566160/

相关文章:

c++ - 无法写入串行设备,但可以读取

c - 关于进程内存中的变量

python - 为什么这个函数装饰器失败了?

Python: 'NoneType' 对象不可下标'错误

Python 3.3 : Can't get a function to return anything other than None

c - 两个 gettimeofday() 调用的差异给出负数

c - 从 C 文件中读取特定行数(scanf、fseek、fgets)

c++ - 如何在 VS 2017 中编译其他编译器的代码

python - 与 None 变量类型的比较

python - 为什么在输出中打印 'None'?