Search code examples
cnonetype

C equivalent of Python None type


Is there C data type that is equivalent to Python None type?

I tried to search for it on the internet but I couldn't really find anything.

Thank you,


Solution

  • Python is dynamically typed so you can bind a variable name to any type, such as string, numeric, or NoneType. As C is statically typed, variables are locked to a specific type, but there's nothing stopping you from creating a type able to be any type.

    For example, a union with a tag field to indicate the type, such as in the following complete program. First, the tag and union types which allow you to store and select any of the types:

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

    Then some helper functions to set the uber-type to a specific typed value:

    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;
    }
    

    And, finally, a test harness, including an output function:

    #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;
    }
    

    The output of the test harness main is, as expected:

    none:
    int:42
    double:3.141590