+ 1
String switch case statements in C?
Is it possible to use strings for cases in c? How does it work or is there a work around? I know I can do a bunch of if statements but would like to know if cases statements are possible. Thanks. Something like... Switch(string) Case: "yes"; Printf("you chose yes"); Break; Case: "no"; Printf("you chose no");
12 Respuestas
+ 3
Benjamin Davis it is possible but not recommended unless speed and memory are highest priority, and maintainability and portability are lowest priority.
In other words, this is a hack!
Because switch and case values only may be integral values, then consider that you could treat the char array pointer as an integer pointer. Then you can compare up to eight bytes at once as a single long int value.
Here is a demonstration of using string as an int pointer to compare up to 4 bytes in a switch statement:
https://code.sololearn.com/cfp1a5hjXy0w/?ref=app
+ 4
No, in C switch cases need to be constant integral numeric values (C Standard 6.8.4.2). Strings are unfortunately not possible. I don't see another way but to use strcmp or strncmp to do the string comparisons.
+ 3
Brian This code is not only non-portable, but also contains a bug. If the `string` variable points to a memory containing for example {'n','o','\0','a'}, the second case block won't execute, whereas it should, as the memory contains proper null-terminated string "no".
+ 2
Thats currently what im doing I was just hoping it was possible. Thank you. 🤜
+ 2
Евгений yes, that is a bug. I should have initialized the array with zeros. Good catch! I will fix it and try to be more careful when writing quick demo code.
+ 2
Brian In this particular case initialization with zeros will help. But as a general solution, this won't work, as one can't be sure about the contents of the memory where the string for comparison is located.
+ 2
Benjamin Davis the potential bug was in failing to ensure the fourth byte of the array would be '\0'. After scanf stored the first three ("no\0"), the fourth one had never been initialized, so when doing the integer comparison, the random value could make the comparison fail.
+ 2
Benjamin Davis
the good old if-else is still your most useful fallback.
also, as to why no strings in switch...
https://www.edureka.co/community/186509/why-can-t-the-switch-statement-be-applied-on-strings#:~:text=Strings%20are%20not%20supported%20as,code%20for%20a%20switch%20statement.
https://code.sololearn.com/cE4vRN6nS0b1/?ref=app
+ 2
Benjamin Davis I would say it's not just a fallback, it's the only proper solution.
0
Alright much appreciated! I still got a ton to learn. I'm just getting into learning pointers. I'm curious why no would be a bug? That's confusing... and it's interesting to see pointers used that way.
0
Games below
0
Yes