-2

I am always tempted to refer to void * as dynamic typing for C & C++, usually as a throwaway joke.

I could not find a wikipedia entry or a dictionary entry for Dynamic Type. Perhaps the term is non-sensical?


Questions:

  1. Is void * a dynamic type?
  2. Is QVariant a dynamic type?

Thanks.

7
  • 1
    Related: Representing dynamic typing in C Commented Jan 23, 2023 at 11:27
  • 3
    C++ does not have dynamic types. The type of everything is fixed at compile time. void * can be used for a technique called "type erasure" where a portion of the code has no knowledge of the type of the object (it obviously can't make use of the object as it doesn't know what type it is). Commented Jan 23, 2023 at 11:30
  • 2
    As for "Is void* a dynamic type?", that question doesn't make any sense if you can't answer "what is a dynamic type"? As far as I know, no such thing exists in C or C++. Probably why no wikipedia page exists either. There is dynamic type checking however, is that what you are asking about?
    – Lundin
    Commented Jan 23, 2023 at 11:38
  • 1
    re QVariant - "...The QVariant class acts like a union for the most common Qt data types...." - it's union wrapper for a few fixed Qt types. So not dynamic at all. The types QVariant can hold are fixed: (a) by design of Qt and (b) at compile time. See also std::variant. ps the QVariant link in the question is broken. Commented Jan 23, 2023 at 11:57
  • @RichardCritten For it to be dynamic, does it have to be able to become literally any type, or is it allowed to be constrained to a select few?
    – Anon
    Commented Jan 23, 2023 at 12:04

1 Answer 1

0

Note this answer assumes dynamic type conversion as definition

void* is not a dynamic type, it is a pointer without a type, that doesn't make it a dynamic type because it's type does not automagically adapt to the situations as in Javascript.

For example such code wouldn't work at all:

void* test = malloc(20);
test[0] = 'E'; /* dereferencing void pointer */
puts(test);

Void pointers has to be casted by the programmer and in a sense that what would "dynamic" correspond to is not dynamic.

Some of C Compilers may cast void into other types automatically at compile time but that wouldn't make it dynamic.

Technically speaking similar thing can be done with char* too and you can convert it into a int and that wouldn't make it dynamic.

char* e = malloc(sizeof(int));
memset(e, 0, sizeof(int));
int coolint = *(int*)(e);
printf("%d", coolint);

It's better to think void* like an any type, anything stored in your computer's memory is represented by bytes and by themselves they do not correspond to any type they are just numbers make up the data.

Main usage area of void* in C is to emulate polymorphism.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.