user1998844
user1998844

Reputation: 467

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 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

Answers (3)

Lundin
Lundin

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

Ajay Brahmakshatriya
Ajay Brahmakshatriya

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

BusyProgrammer
BusyProgrammer

Reputation: 2781

invalid conversion from void* to int*

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

Related Questions