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 )
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.
Yes, obviously.
(void)p;
means the object is getting casted to void
type, (which is not a complete type) and that being the complete expression, the result of the expression should not be used, hence compiler does not check for it's usage.
Quoting C11
standard, chapter 6.3.2.2, void
The (nonexistent) value of a
void
expression (an expression that has type void) shall not be used in any way,[......] If an expression of any other type is evaluated as avoid
expression, its value or designator is discarded.
So, no warning or error is generated.
OTOH,
(void *)p;
means the object is a pointer to void
type, which is a complete type and should be used in your program. In that case, the non-usage of the object out of the expression is rightly reported by the compiler.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.