0
How to understand this code?
#include <iostream.h> void increase (void* data, int type) { switch (type) { case sizeof(char) : (*((char*)data))++; break; case sizeof(short): (*((short*)data))++; break; case sizeof(long) : (*((long*)data))++; break; } } int main () { char a = 5; short b = 9; long c = 12; increase (&a,sizeof(a)); increase (&b,sizeof(b)); increase (&c,sizeof(c)); cout << (int) a << ", " << b << ", " << c; return 0; }
1 Answer
+ 4
A void pointer is a special pointer that can point and be casted to any generic type, as it has no type at all in general.
But this makes it impossible for such a pointer to be dereferenced directly, or to perform arithmetic operations like increment and decrement.
Thus, such a pointer is used by casting it to a different type and then dereferencing it.
In your case, you pass a type of pointer and its size to the function. The function then stores your argument in a void pointer as casts it accordingly as per the switch cases for the size.
The line ((char*)data), will cast the void pointer to a char pointer if the size of the pointer is received as 1.
The rest of the part dereferences he casted pointer and increments the value.