Quantcast
Viewing latest article 27
Browse Latest Browse All 40

Answer by Zan Lynx for Does C have an equivalent to var?

Scripting languages which are written in C manage to implement this for their variables. However, it is quite complicated.

C needs to know the size of things, so that it can place them into memory correctly. A variable must always be of a known type and size.

In order to have a variable of unknown type, you need to create a struct something like this (off the top of my head, untested but see https://github.com/zlynx/type-union-test):

struct var {    enum {        INT,        OBJ,        DOUBLE,    };    union {        long i;        void* p;        double d;    };};

And then functions to operate on everything. Implementing OBJ gets fun because you need more structs defining if it is an array or another var, etc.

Anyway. If you're looking to make programming in C easier then don't try this. Decide up front what your variable is.


Viewing latest article 27
Browse Latest Browse All 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>