Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C switch case using char[2]

I’m trying to use switch case with char[2] in C, but it only supports integers.

int main() {
        char c[2] = "h";
        switch (c) {
                case "h":
                        printf("done!");
        }
        return 1;
}

For better understanding, what I’m trying to do is:

if "h" in ")($+#&@+)#"

Basically I want to make a condition that matches a character with a group of characters, but efficiently, the first thing that came to mind is to use switch case but it only supports int. But when I use (int)c which is recommended in other stackoverflow answers, it doesn’t return the ascii value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t compare arrays of characters (strings) using a switch statement directly, because switch statements only work with fundamental types; not arrays of fundamental types.

The reason using (int)c isn’t returning the ASCII value is because you’re casting char[]->int instead of char->int.

You can try looping through the array and comparing each character with a switch statement instead:

char c[2] = "h";
bool found = false;
for (int i = 0; !found && i < 2; ++i) {
    switch (c[i]) {
    case 'h':
        found = true;
        printf("Done!");
        break;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading