Skip to content

Instantly share code, notes, and snippets.

@dragon0
Created December 1, 2017 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dragon0/0d2e740e2bb50d46a2f36f515afb1071 to your computer and use it in GitHub Desktop.
Save dragon0/0d2e740e2bb50d46a2f36f515afb1071 to your computer and use it in GitHub Desktop.
A union type demonstrating an int and a float occupying the same memory location
#include<iostream>
#include<sstream>
int main(int argc, char** argv){
union mytypes_t {
int i;
float f;
} mytypes;
int in_i = 5;
float in_f = 5.0;
std::stringstream in;
if(argc > 1){
in << argv[1];
in >> in_i;
in.str("");
in.clear();
}
else{
in_i = 5;
}
mytypes.i = in_i;
std::cout
<< "mytypes.i = "
<< mytypes.i
<< " (0x"
<< std::hex
<< mytypes.i
<< std::dec
<< ")"
<< std::endl;
std::cout << "mytypes.f: " << mytypes.f << std::endl;
if(argc > 2){
in << argv[2];
in >> in_f;
in.str("");
in.clear();
}
else{
in_f = 5.0;
}
mytypes.f = in_f;
std::cout << "mytypes.f = " << mytypes.f << std::endl;
std::cout
<< "mytypes.i: "
<< mytypes.i
<< " (0x"
<< std::hex
<< mytypes.i
<< ")"
<< std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment