I'm getting a warning ([-Wmaybe-uninitialized]) on some code that I don't think should be throwing a warning. Compiling with cmake using GCC. Basically it's saying that a variable may not be initialized, but I think it's guaranteed to be initialized. Here's an example:
#include<iostream>
enum class ByteOrder
{
little_endian,
big_endian
};
class someClass
{
someClass(ByteOrder order = ByteOrder::little_endian) :
kOrder{order}
{}
void someFunc();
private:
const ByteOrder kOrder;
};
void someClass::someFunc()
{
int i;
switch(kOrder)
{
case ByteOrder::little_endian:
i = 0;
break;
case ByteOrder::big_endian:
i = 1;
break;
}
std::cout << i;
}
According to GCC, i at the line
std::cout << i;
could be uninitialized. But I don't see how that's possible since there are only two options in the switch statement. I tried setting ByteOrder to nullptr but that didn't work. Am I missing something here?
To illustrate the comments to your question, try this:
const ByteOrder kOrder = (ByteOrder)3;
Bottom line: just add the default: case, you may want to throw from there.
Everyone had great input on this. I ended up solving this by just initializing my variable to an arbitrary value. We didn't want to use default because we wanted to keep the warnings that show up when you don't have an exhaustive switch statement for an enum. Thanks to everyone for answering.