Void pointer in function call in C ++ vs C

I have this piece of code that works in C but not C ++, is that any way to make it work in 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. 

WITH

 1000 

Please, help

+5
source share
3 answers

invalid conversion from void* to int*

To do the conversion from void* to int* , you will need to distinguish b as int* when assigning it to c . At:

 int *c = (int*) b; 

This works in C ++ and C.

+9
source

C allows an implicit conversion between void* and any pointer to an object type, C ++ does not. To make your code compatible with both languages, you can enter foo( (void*)&a ); .

However, using void pointers is not recommended in both languages ​​- they should be used only as a last resort. If you want the function to be typical of C, you should use the _Generic keyword. In C ++ you use templates.

+4
source

Given all the casting problems in both languages, the correct way is

 #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); 
+1
source

Source: https://habr.com/ru/post/1266248/


All Articles