float number = 1.0;
float* number_pointer = &number;
int* int_pointer = (int*) number_pointer;
*int_pointer += 30;
printf("%f \n",number);
What does the line (*int_pointer)+= 30;
do here?
float number = 1.0;
float* number_pointer = &number;
int* int_pointer = (int*) number_pointer;
*int_pointer += 30;
printf("%f \n",number);
What does the line (*int_pointer)+= 30;
do here?
I see two questions there.
What happens when you use
int* int_pointer = (int*) number_pointer;
That line takes the address of an object that holds a float
and stores that address in int_pointer
. At this point, the compiler will be able to treat the address as though it holds an integer. That constitutes a violation of the strict aliasing rule.
What happens when you use
*int_pointer += 30;
It increments the value of the object that int_pointer
points to by 30
. In cases where int_pointer
points to a valid int
object, that operation will be fine. In your case, this will cause undefined behavior since int_pointer
really points to an object of type float
.
Let me explain each statement:
float number = 1.0;
Here you have declared and initialized a float variable called number
.
float* number_pointer = &number;
Declared and initialized float type pointer number_pointer
to number
. This means number_pointer
holds the address of the variable number
and *number_pointer
gives the value of the variable number
, i.e., 1.0
.
int* int_pointer = (int*) number_pointer;
Type-casted float pointer number_pointer
to integer pointer and initialized to int_pointer
. After this explicit type-casting, the value of *int_pointer
is not 1.0
but its corresponding integer 1065353216
.
*int_pointer += 30;
This is a short hand for *int_pointer = *int_pointer + 30;
. *int_pointer
becomes 1065353246
.
printf("%f \n",number);
Prints the value of number
, which is now 1.000004
and not the initial 1.000000
. The change is caused by the addition performed on int_pointer
which points to where number_pointer
is pointing which in turn is the variable number
.