Created
December 1, 2017 23:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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