Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typecast to (void *) when passing pointer to object

Consider the following snippet:

void my_func(int a, void *b);
...

struct my_struct s = { };
my_func(10, (void *)&s);

Is it necessary to typecast to (void *) when passing &s to the function?

like image 851
Mark Avatar asked Jan 27 '23 21:01

Mark


2 Answers

A pointer to any type may be freely converted to or from a void * without a cast.

Section 6.3.2.3p1 of the C standard states:

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

The only time a cast is needed is if you pass a pointer to a variadic function like printf where an implicit conversion can't occur, since it won't know what the exact type being passed in is.

Note that, as with any pointer type, you can't "remove" a qualifier such as const when passing to a function without a cast. Sections 6.3.2.3p2 states:

For any qualifier q, a pointer to a non-q-qualified type may be converted to a pointer to the q-qualified version of the type; the values stored in the original and converted pointers shall compare equal.

like image 52
dbush Avatar answered Feb 12 '23 19:02

dbush


you do not have to with some exceptions as you may get the warning if the object which reference you pass to the function is volatile or const - generally has different attribute.

void ee(void *q)
{
    pritntf("%p", q);
}

volatile int g;
const int f;

int main()
{

    ee(&g);
    ee(&f);
}

gives this warnings:

<source>: In function 'main':

<source>:17:8: warning: passing argument 1 of 'ee' discards 'volatile' qualifier from pointer target type [-Wdiscarded-qualifiers]

     ee(&g);

        ^~

<source>:6:15: note: expected 'void *' but argument is of type 'volatile int *'

 void ee(void *q)

         ~~~~~~^

<source>:18:8: warning: passing argument 1 of 'ee' discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]

     ee(&f);

        ^~

<source>:6:15: note: expected 'void *' but argument is of type 'const int *'

 void ee(void *q)

         ~~~~~~^

Compiler returned: 0
like image 41
0___________ Avatar answered Feb 12 '23 20:02

0___________