Reputation: 160
I have found that code that works (although with warning) in C is now giving me an error when moved to C++. I'd like to know why this produces an error, and how to resolve.
I am converting someone elses code to C++ and this gave me the error (pulled out and tested in its own file)...
#include <stdio.h>
typedef enum SPI_SSADDR_TYPE
{
SSADDR0 = 0,
SSADDR1 = 1,
SSADDR2,
SSADDR3,
SSADDR4,
SSADDR5,
SSADDR6,
SSADDR7,
SSADDR8
} SPI_SSADDR;
void SPI_set_slave_addr( SPI_SSADDR slaveSelectAddr );
int main()
{
SPI_set_slave_addr(SSADDR8);
return 0;
}
void SPI_set_slave_addr( SPI_SSADDR slaveSelectAddr )
{
slaveSelectAddr = slaveSelectAddr & (SPI_SSADDR)(0x07); // This line
printf("Test: %d\r\n", slaveSelectAddr);
return;
}
The error it produces is:
TypeDef.cpp: In function ‘void SPI_set_slave_addr(SPI_SSADDR)’:
TypeDef.cpp:26: error: invalid conversion from ‘int’ to ‘SPI_SSADDR’
Upvotes: 1
Views: 1035
Reputation: 254461
In C++, unlike in C, you can't implicitly convert an integer type into an enumeration type. The result of the expression is an integer type, since enumerations are converted to integers when you perform arithmetic on them, and so must be explicitly converted back:
slaveSelectAddr = static_cast<SPI_SSADDR>(slaveSelectAddr & 0x07);
Upvotes: 4
Reputation: 3908
Try this:
slaveSelectAddr = (SPI_SSADDR)((int)slaveSelectAddr & 0x07);
Upvotes: 1
Reputation: 11058
slaveSelectAddr = static_cast<SPI_SSADDR>(static_cast<int>(slaveSelectAddr) & 0x07);
Upvotes: 0
Reputation: 308186
Try moving the cast:
slaveSelectAddr = (SPI_SSADDR)(slaveSelectAddr & 0x07);
You can also use a more C++ version of the cast:
slaveSelectAddr = static_cast<SPI_SSADDR>(slaveSelectAddr & 0x07);
Upvotes: 0