How can I rewrite this code in such a way that user is always shown the correct state(CA,AL etc.) string whenever he passes a valid direction.
i.e How do I make sure there is a valid case statement for each of those enum_types in the directions enum during compile time than in runtime?
For. Eg. I have intentionally commented out the case statement for east. Is there a way to catch this at compile time.
My gut feel is (NO) that this is why the language provides a default case and hence this may not be possible. But I’ll leave this to the experts.
#include <iostream>
#include <string>
using namespace::std;
typedef enum
{
min_dir = -1,
north,
south,
east,
west,
}directions;
directions get_direction( string user_choice)
{
if(user_choice == "north")
{
return north;
}
else if (user_choice == "south")
{
return south;
}
else if (user_choice == "east")
{
return east;
}
else if (user_choice == "west")
{
return west;
}
else
{
return min_dir;
}
}
int main()
{
string user_direction;
cout << "Enter direction\n";
cin >> user_direction;
directions my_dir = get_direction(user_direction);
cout << " Print direction's description\n";
if( my_dir == min_dir)
{
// User passed junk
return -1;
}
switch(my_dir)
{
case north:
cout << "North - New york\n";break;
case south:
cout << "South - Alabama\n";break;
// case east:
// cout << "East - North Carolina\n";break;
case west:
cout << "West - California\n";break;
default:
cout << "Should Ideally never get here\n";break;
}
system("pause");
return 0;
}
Edit:
This is just an example to illustrate the point. This for code at work. They have compile this both in Windows(MSVC) and linux (gcc). Would this only be a warning? I’ll need a stricter enforcement.
Can I write some code that will error out during a make process if an enum doesn’t have a case statement?
In GCC (g++) and Clang, there is
-Wswitch-enum, which will warn you if you do not have acasefor a possible value for theenumtype you’reswitching over (even if you have adefaultcase).In MSVC, there is the comparable C4062 which comes from warning level 3, but it will not warn you if you have a
defaultstatement. If you want warnings in that case, you need to enable the level 4 warning C4061, which produces a warning when an enumerated value is missing, even if a default case is provided.As far as making it an error goes: all compilers have a “treat warnings as errors” option. In GCC and Clang, it’s
-Werror; in MSVC, it’s/WX.