vkchavda
vkchavda

Reputation: 93

function call, casting its void * argument to any other type

there is this question on stack overflow Why type cast a void pointer? I want to ask relevant question on comment but I don't allow as I am newbie here. My question is in the second answer given by Guillaume, there is this function.

void some_function(void * some_param) {
    int some_value = *((int *) some_param); /* ok */

Can I do like this

// function defination

void some_function(void * some_param) {
    int some_value = *some_param;

// calling function, casting in argument

some_function((int *) some_param);

Thanks

Upvotes: 2

Views: 753

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

In this call

some_function((int *) some_param);

the function argument is implicitly converted to the type of the parameter that is void *. So the casting is redundant and this statement within the function

int some_value = *some_param;

is invalid.

According to the C Standard (6.3.2.2 void)

1 The (nonexistent) value of a void expression (an expression that has type void) shall not be used in any way, and implicit or explicit conversions (except to void) shall not be applied to such an expression. If an expression of any other type is evaluated as a void expression, its value or designator is discarded. (A void expression is evaluated for its side effects.)

And this expression

*some_param

has the type void within the function

void some_function(void * some_param) {
    int some_value = *some_param;
    //...
}

As for the question

During function call, can I cast its void * argument to any other type in ANSI C

You may assign a pointer of the type void * to pointer to object of any other type without casting or you may cast a pointer of the type void * to any object pointer type..

Upvotes: 2

Related Questions