Skip to content

Instantly share code, notes, and snippets.

@Infinitusvoid
Created January 15, 2023 20:02
Show Gist options
  • Save Infinitusvoid/e1d58cc784362fd9c127e239dddc21c3 to your computer and use it in GitHub Desktop.
Save Infinitusvoid/e1d58cc784362fd9c127e239dddc21c3 to your computer and use it in GitHub Desktop.
C++ : Type punning examples
#include <iostream>
struct Entity
{
int x;
int y;
int* get_position()
{
return &x;
}
};
int main()
{
Entity entity = { 10, 25 };
std::cout << entity.get_position()[0] << "\n"; //10
std::cout << entity.get_position()[1] << "\n"; //25
int* pos = (int*)&entity;
std::cout << pos <<"\n"; //adress
std::cout << *(pos) << "\n"; // 10
std::cout << *(pos + 1) << "\n"; // 25
std::cout << pos[0] << "\n"; // 10
std::cout << pos[1] << "\n"; // 25
int y = *(int*)((char*)&entity + 4);
std::cout << y << "\n"; // 25
//if you wish just to access the value
{
int& value = *(int*)&entity;
std::cout << "value : " << value << "\n";
}
{
int& value = *((int*)&entity + 1);
std::cout << "value : " << value << "\n";
}
{
int& value = *((int*)&entity + 1);
value += 100;
}
{
int& value = *((int*)&entity + 1);
std::cout << "value : " << value << "\n"; //125
}
{
std::cout << "entity.y : " << entity.y << "\n"; //125
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment