You take the address of foo
and cast it to pointer to int
.
If foo
and p
are of different types, the compiler might issue a warning about type mismatch. The cast is to supress that warning.
For example, consider the following code, which causes a warning from the compiler (initialization from incompatible pointer type
):
float foo = 42;
int *p = &foo;
Here foo
is a float
, while p
points to an int
. Clearly - different types.
A typecasting makes the compiler treat one variable as if it was of different type. You typecast by putting new type name in parenthesis. Here we will make pointer to float
to be treated like a pointer to int
and the warning will be no more:
float foo = 5;
int *p = (int*)(&foo);
You could've omitted one pair of parenthesis as well and it'd mean the same:
float foo = 5;
int *p = (int*)&foo;
The issue is the same if foo
is a function. We have a pointer to a function on right side of assignment and a pointer to int
on left side. A cast would be added to make a pointer to function to be treated as an address of int
.