Mark
Mark

Reputation: 6464

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?

Upvotes: 4

Views: 797

Answers (3)

dbush
dbush

Reputation: 223699

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.

Upvotes: 5

0___________
0___________

Reputation: 67476

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

Upvotes: 2

markzz
markzz

Reputation: 1252

No, it is not required, it just makes the code clearer on what exactly is being passed to the function.

Upvotes: 1

Related Questions