I saw this example on a website, and on sites it is mentioned: "One of its uses (void pointers) may be to pass general parameters to a function"
#include <iostream>
using namespace std;
void increase (void* data, int psize)
{
if ( psize == sizeof(char) )
{ char* pchar; pchar=(char*)data; ++(*pchar); }
else if (psize == sizeof(int) )
{ int* pint; pint=(int*)data; ++(*pint); }
}
int main ()
{
char a = 'x';
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
cout << a << ", " << b << endl;
return 0;
}
Isn't it easier to write code as shown below?
void increaseChar (char* charData)
{
++(*charData);
}
void increaseInt (int* intData)
{
++(*intData);
}
int main ()
{
char a = 'x';
int b = 1602;
increaseChar (&a);
increaseInt (&b);
cout << a << ", " << b << endl;
string str;
cin >> str;
return 0;
}
This is less code and really simple. And in the first code I had to send the data type size here, I do not!
w4j3d source
share