I hear that C isn't so type-safe and I think that I could use that as an advantage for my current project.
I'm designing an interpreter with the goal for the VM to be extremely fast, much faster than Ruby and Python, for example.
Now I know that premature optimization "is the root of all evil" but this is rather a conceptual problem.
Would the following be possible?
struct Value {
ValueType type;
void* value;
}
I would store the actual values elsewhere, e.g: a separate array for strings and integers, value* would then point to some member in this table.
I would always know the type of the value via the type variable, so there wouldn't be any problems with type errors.
Now:
Is this even possible in terms of syntax and typing?
void pointer in C / C++A void pointer can hold address of any type and can be typecasted to any type.
Every pointer is of some specific type. There's a special generic pointer type void* that can point to any object type, but you have to convert a void* to some specific pointer type before you can dereference it.
There are majorly four types of pointers, they are: Null Pointer. Void Pointer. Wild Pointer.
The Pointer in C, is a variable that stores address of another variable. A pointer can also be used to refer to another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/ previous memory location. The purpose of pointer is to save memory space and achieve faster execution time.
Yes, you can use a void*
to point to anything, and then cast it to the proper type when needed (that's how malloc
and such can work).
void*
is basically "pointer to an arbitrary block of memory".
If you know the range of types you want to support, this could easily be done with a union
to avoid casts all over the place:
struct Value
{
ValueType type;
union
{
int* iptr;
char* sptr;
float* fptr;
struct map* mptr;
/* ... */
void* vptr; /* catch all, extensions */
} ptrs;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With