Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to avoid a lot of switch case

2 views
Skip to first unread message

silusi...@gmail.com

unread,
May 30, 2008, 2:26:34 AM5/30/08
to
I wrote ,as homework, a program that displays words after key pressed.
So, if letter 'A' is pressed, the word 'dog' appears; if letter 'B' is
pressed 'cat' appears; if letter 'a' is pressed 'apple' appears; and
so on...
I wrote this program with a lot of switch case, so i want to obtain a
smaller program (if possible)...can you help me?

Szabolcs Borsanyi

unread,
May 30, 2008, 2:52:53 AM5/30/08
to

What you would like to do is to map integers to strings.

How about an array?
const char *my_lovely_words[UCHAR_MAX];

Please stop reading here, try to write the program, and then you may continue.

my_lovely_words['a']="apple";
...
But I do not see how that would save you much keystrokes.

In C99 you can have named initialisers
const char *my_lovely_words[]={
['A']="dog",
['a']="apple",
};

Szabolcs


vipp...@gmail.com

unread,
May 30, 2008, 4:43:07 AM5/30/08
to
On May 30, 9:52 am, Szabolcs Borsanyi <s.borsa...@sussex.ac.uk> wrote:

> On Thu, May 29, 2008 at 11:26:34PM -0700, silusilus...@gmail.com wrote:
> > I wrote ,as homework, a program that displays words after key pressed.
> > So, if letter 'A' is pressed, the word 'dog' appears; if letter 'B' is
> > pressed 'cat' appears; if letter 'a' is pressed 'apple' appears; and
> > so on...
> > I wrote this program with a lot of switch case, so i want to obtain a
> > smaller program (if possible)...can you help me?
>
> What you would like to do is to map integers to strings.
>
> How about an array?
> const char *my_lovely_words[UCHAR_MAX];
>
> Please stop reading here, try to write the program, and then you may continue.
>
> my_lovely_words['a']="apple";
And what if 'a' has the value 4325? It would waste a lot of space.
Here's another solution:

const char *my_lovely_words[] = { ... };
const char *p, str[] = "#Az";
int c;
...
if(p = strchr(str, c)) != NULL) printf("%c = %s\n", c,
my_lovely_words[p - str]);

0 new messages