-1

I have an array and a function that gets a char, this char should stand for a specific index in the array. for example, 'a' stands for index 0, 'b' stands for index 1 'c' stands for index 2...

I don't want to use a switch case!

void func(char ch, object* arr)
{
    int index = ch//do something
    arr[index]
}

Is there any way to do it without switch case, elegant way that won't take many lines of code.

וי חנ
  • 79
  • 6

2 Answers2

1

You can do this by getting the ASCII value of that character.

void func(char ch, object* arr)
{
    int index = (int)ch;  //If the ch is 'a', This will return a value of 97(the ascii of lower-case a).
    arr[index];
}

if you want the index to start from 0 instead of 97, simply subtract the index by 97:

int index = (int)ch - 97;

Or better:

int index = ch - 'a';

Check this link to see the ASCII table.

0

I would suggest using ASCII codes, see: https://www.ascii-code.com. For instance, if char c is given by a user then it is a printable char so the codes relevant to you are between (space, 32) -> (delete, 127). Although your array size is limited to 95 entries if you use this you can approach any valid cell in your object array in that range. arr[c-' '] <=> arr[0] No need for lengthy if/else/switch cases.

Liad Mazor
  • 1
  • 1
  • 2