I know you already solved this, but I’m guessing from your code that what you actually wanted was compass directions.
Instead of using char
you’d be better off using an enum class
.
(I apologise in advance if this is a lot to take in.)
For example:
enum class Direction : char { None, North, South, East, West };
Which you can then use like:
Direction x;
if (y == 0) { x = Direction::North; }
else if (y == 1) { x = Direction::South; }
else if y == 2 { x = Direction::East; }
else if == 3 { x = Direction::West; }
Or better yet:
Direction x;
switch(y)
{
case 0: x = Direction::North; break;
case 1: x = Direction::South; break;
case 2: x = Direction::East; break;
case 3: x = Direction::West; break;
}
Even better than that, wrap that in a function:
Direction NumberToDirection(const char & c)
{
switch(c)
{
case 0: return Direction::North;
case 1: return Direction::South;
case 2: return Direction::East;
case 3: return Direction::West;
default: return Direction::None;
}
}
And use it like x = NumberToDirection(y);
.
An enum is basically the same as a number (char, int, etc), but instead of having ‘magic numbers’ with a non-obvious meaning, each value is given a name and you don’t have to worry about what the numbers actually are. In addition they have what is called ‘type safety’. An enum class
value can only be assigned to a variable of the same type.
e.g.
enum class Direction { North, South, East, West };
enum class Colour { Red, Blue, Green };
Direction variable = Colour::Red; // Won't compile
If you want, you can also say what number you want each value to represent. Using the direction example again:
enum class Direction : char
{
North = 0,
South = 1,
East = 2,
West = 3
};
Which means you can then do:
Direction x = static_cast<Direction>(y);
So that big chain of if statements can be reduced to a single static_cast
. Make sure that y
is in the correct range though, using a value other than 0
, 1
, 2
or 3
could cause errors.