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 )
Any pointer to an object, optionally type-qualified, can be converted to void* , keeping the same const or volatile qualifications.
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.
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.
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)); // ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With