Reputation: 467
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
Upvotes: 5
Views: 1906
Reputation: 214310
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.
Upvotes: 4
Reputation: 9203
Considering all the casting issues with both the languages, the correct way would be -
#ifdef __cplusplus
#define cast_to_intp(x) static_cast<int*>(x)
#else
#define cast_to_intp(x) (x)
#endif
And then use
int *c = cast_to_intp(b);
Upvotes: 1
Reputation: 2781
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.
Upvotes: 10