I have a problem with my code, I have a struct inside a union and it lets me assign values to it but when I try to read the value or assign it to another variable it doesn't work it puts a blank value
#include<iostream>
#include<cstdint>
using namespace std;
typedef union {
struct{
uint8_t lo;
uint8_t hi;
};
uint16_t value;
}Register;
int main(){
Register AF;
AF.lo = 0xF0;
AF.hi = 0xF0;
cout<<AF.hi<<endl;
cout<<AF.value<<endl;
return 0;
}
the output of the program is this:
frijol@frijolito:~/GameBoyEmulator/src$ g++ test.cpp
frijol@frijolito:~/GameBoyEmulator/src$ ./a.out
61680
frijol@frijolito:~/GameBoyEmulator/src$
What can I do to access each value independently without using bitwise?
The problem occurs because you are trying to print a value of type uint8_t with std::cout .
The std::cout function has, among others, two versions, one that receives a char and one that receives an unsigned int . Since uint8_t is usually an alias of char (defined with a typedef), calling std::cout with an argument of type uint8_t calls the version that receives a char , which prints a character, and not the one that receives an unsigned int , which prints an unsigned integer.
To get it to call the correct version, you can do a type conversion using the static_cast operator :
Unions can only have one member active at a time, it is undefined behavior to assign one member of the union and read from the other.
As can be read in the C++ standard (translation and emphasis mine):
Therefore, this code starts the life cycle of the members
Register::lo
andRegister::hi
:And the following code reads information from a data whose life cycle has not started:
Which is undefined behavior and can lead to the behavior you describe.