Reputation: 19
I'm trying to understand this line of code. Can someone help me? Is it saving the result in the variable val or in the address of the variable val?
*((int*)(&val) +1)= A*(y) + (B - C)
Thank you
Upvotes: 0
Views: 2225
Reputation: 17
I hope others have answered your question. Adding to what others have said, the same code can be written as follows:
(int*)(&val)[1]= A*(y) + (B - C)
where (int*) will type cast &val as an implicit pointer to an integer which points to the address of val and [1] indicates the first integer location ahead of the location where val is stored.
This is how arrays are interpreted. Say you have an array
int a[10];
For this array, 'a' is a pointer which points to the base address ( address of the element a[0] ), and a[i] is nothing but *(a+i), i.e. the element which is i locations ahead of the first element of the array.
Upvotes: 1
Reputation: 23774
Imagine this class:
class A {
int number = 10;
public:
void print(){ std::cout << number; }
};
The int number
is private for the access not the use!
So how can we access this private int
.
Simply:
A obj;
*( (int*) ( &obj ) ) = 100;
obj.print();
output
100
Now if you would have more than one data then how to access?
by this syntax:
*((int*)(&val) +1)
It says:
find the address of the first data,
one index go ahead,
cast it to the int*
,
then dereference it,
then initialize it
Upvotes: 0
Reputation: 4369
Divide expression *((int*)(&val) +1)
into smaller ones to understand it:
val
(&val)
and treat it as a pointer to an int (int *)
+1
to this pointer which means 'move pointer to next int' as it was an array of ints.*
and =
apply right hand side expression to int
pointed by pointer.Upvotes: 2
Reputation: 3849
&val
take the address of val
(int*)(&val)
consider this address as a pointer to int
(int*)(&val) +1
increment this address by 1 (times sizeof(int)
)
*((int*)(&val) +1) = ...
assign the right hand side value at this incremented address
Upvotes: 9
Reputation: 126777
It is interpreting val
as if it was an array of integers, and storing the result of the right hand expression in its second element. To understand exactly the point of it all you should provide some more context (my guess: is it manipulating the raw content of double
values?)
Notice that, depending on the type of val
, this may be undefined behavior due to strict aliasing rules.
Upvotes: 3