I have an odd problem when using the return result of a function and the += operator. The function is very simple, one line that fetches a unsigned char value from an array. When I use the = operator to place it into a variable, the value comes out correct. However, using the +=, the value comes out to be garbage.
Here is my code:
unsigned short value = 0;
value = this->memory->get(address) << 8; //this will work
value += this->memory->get(address) << 8; //this will set it to 52480 every time
unsigned char Memory::get(unsigned int address)
{
return this->memory[address];
}
I figured that initializing value to zero would solve the problem; however, it does not. Also, casting the return to unsigned short still does not solve it.
An unsigned char is not big enough to be shifted 8 bits on virtually every platform. This is undefined behaviour, to shift larger than the byte size.