How can I express in C a map like this one?
{
{1, "One"},
{1000, "One thousand"},
{1000000, "One million"}
}
The key is an int and can be a big int, the value is a constant string and it is known at compile time.
The map will contain some 20 or 30 elements.
I would write this function:
const char* numbers( const int i )
{
switch( i ) {
case 1: return "One";
case 1000: return "One thousand";
case 1000000: return "One million";
default: return "";
}
}
is there any better (more idiomatic) way of doing it?
Using a switch is entirely idiomatic C, there’s a separate style consideration (that would apply in pretty much any language) whether you want to separate the key/value data out of the program logic.
You could use an array of
const struct { int key; const char *value; };, but then you’ll start worrying about whether you should use a linear search, binary search, perfect hash, etc. With a switch, the compiler takes it out of your hands.If you have some kind of associative container (tree or hashmap) that you use for other things in this project then you could use that, but it’s not really worth writing one for a 30-item collection.