#include<stdio.h>
int main(){
char name[20];
printf("enter a name ");
scanf("%s",name);
switch(name[20]){
case "kevin" :
printf("hello");
break;
}
printf("%s",name);
getch();
}
It seems it will not work. Is this possible? I mean is there any way we can make a switch statement of a string. How to solve the problem, actually?
The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String. equals method; consequently, the comparison of String objects in switch statements is case sensitive.
Yes, you can pass an array to a switch.
No you can't. The case labels of a switch need to be compile time evaluable constant expressions with an integral type. But int literals like '+' satisfy that requirement.
You can use char 's for the switch expression and cases as well. In the code below, option matches case 'b' , hence its case block is executed.
Switch statements in C aren't smart like one's found in other languages (such as Java 7 or Go) you cannot switch on a string (Nor can you compare strings with ==
). Switch can only operate on integral types (int
, char
, etc).
In your code you call switch with: switch(name[20])
. That means switch(*(name + 20))
. In other words switch on the 21st char
in name (because name[0]
is the first). As name
only has 20 chars you are accessing whatever memory is after name. (which could do unpredictable things)
Also the string "kevin"
is compiled to a char[N]
(where N
is strlen("kevin") + 1
) which contains the string. When you do case "kevin"
. It will only work if name is in the exact same piece of memory storing the string. So even if I copied kevin
into name. It still would not match as it is stored in a different piece of memory.
To do what you seem to be trying you would do this:
#include <string.h>
...
if (strcmp(name, "kevin") == 0) {
...
}
String compare (strcmp
) returns different values based on the difference in the strings. Eg:
int ord = strcmp(str1, str2);
if (ord < 0)
printf("str1 is before str2 alphabetically\n");
else if (ord == 0)
printf("str1 is the same as str2\n");
else if (ord > 0)
printf("str1 is after str2 alphabetically\n");
Side note: Dont use scanf("%s", name)
in that form. It creates a common security problem use fgets
like this: (there is a safe way to use scanf
too)
#define MAX_LEN 20
int main() {
char name[MAX_LEN];
fgets(name, MAX_LEN, stdin);
...
Switch statements work on int
values (or enum
), but not on char
arrays.
You could do
if (strcmp(name, "kevin")==0) {
printf("hello");
}
else if (strcmp(name, "Laura")==0) {
printf("Allo");
}
else if (strcmp(name, "Mike")==0) {
printf("Good day");
}
else {
printf("Help!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With