C3Morales
C3Morales

Reputation: 19

What does this mean *((int*)(&val) +1)

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

Answers (5)

Naveen Venkat
Naveen Venkat

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

Shakiba Moshiri
Shakiba Moshiri

Reputation: 23774

This is not correct code and you should never use it

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


demo

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

Michał Walenciak
Michał Walenciak

Reputation: 4369

Divide expression *((int*)(&val) +1) into smaller ones to understand it:

  1. take address of val (&val) and treat it as a pointer to an int (int *)
  2. add 1 +1 to this pointer which means 'move pointer to next int' as it was an array of ints.
  3. finaly by combining * and = apply right hand side expression to int pointed by pointer.

Upvotes: 2

O&#39;Neil
O&#39;Neil

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

Matteo Italia
Matteo Italia

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

Related Questions