Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting pointer to void

Tags:

c

pointers

void

Is there any difference in below two castings ?

int a=10;
int *p=&a;

(void)p;          //does not give any warning or error 

or

(void *)p;        //error: statement with no effect [-Werror=unused-value]

when complied with gcc -Wall -Werror --std=c99 -pedantic

Just saw that in this answer. (clearly I misunderstood something )

like image 703
ameyCU Avatar asked Oct 14 '15 14:10

ameyCU


People also ask

Can you cast a pointer to void?

Any pointer to an object, optionally type-qualified, can be converted to void* , keeping the same const or volatile qualifications.

What does casting to void do in C?

Casting to void is used to suppress compiler warnings. The Standard says in §5.2. 9/4 says, Any expression can be explicitly converted to type “cv void.” The expression value is discarded.

Can pointer be casted?

You can cast a pointer to another pointer of the same IBM® i pointer type. Note: If the ILE C compiler detects a type mismatch in an expression, a compile time error occurs. An open (void) pointer can hold a pointer of any type.

How do you pass a void pointer?

The pointer is passed by value, so in f1 you're only changing a copy of the address held by a . If you want to change the pointer, i.e. allocate new memory for the pointer passed in, then you'll need to pass a pointer to a pointer: void f1(void **a) { // ... *a = malloc(sizeof(int)); // ...


1 Answers

When you do

(void) p;

You tell the compiler to simply disregard the result of the expression p. It's effectively the same as an empty statement:

;

When you do

(void *) p;

You tell the compiler to treat the variable p as a generic pointer, and that's the full expression for the statement, an expression which doesn't really do anything and you get the error message.

like image 57
Some programmer dude Avatar answered Sep 26 '22 06:09

Some programmer dude