I have this piece of code that works in C but not C++, is that any way to make it work on both C and C++ ?
void foo(void* b)
{
int *c = b;
printf("%d\n",*c);
}
int main ()
{
int a = 1000;
foo(&a);
return 0;
}
output:
C++:
1 In function 'void foo(void*)':
2 Line 3: error: invalid conversion from 'void*' to 'int*'
3 compilation terminated due to -Wfatal-errors.
C:
1000
Please help
invalid conversion from
void*
toint*
In order to make an conversion from void*
to int*
you will need to cast b
as int*
when assigning it to c
. Do:
int *c = (int*) b;
This works in C++ and in C.
C allows implicit conversion between void*
and any pointer to object type, C++ does not. To make your code compatible with both languages, you could type foo( (void*)&a );
.
However, using void pointers is discouraged in both languages - they should only be used as a last resort. If you want the function to be type-generic in C, you'd use the _Generic
keyword. In C++ you'd use templates.
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