开发者

Can a character array be used as expression for switch statement?

void main()
{
  char name[20];

  printf("\n enter Your Name: ");
  gets(name);

  switch(name)
  {
    default : printf( "Invalid" );
  }

  getch();
}

S开发者_运维问答o my question: is a char array OR Simple array valid in expression for switch and, if it is valid, then what are the case values?


The switch statement is using the address of the character array as the parameter. So no it won't work as you expect it to.

It follows the same reason why you can't throw strings into a switch and expect it to work. (and same with string comparisons)


No, the standard says

The controlling expression of a switch statement shall have integer type.

in your case the address of the string would be taken which is not considered to be an integer in that respect.


No you cannot. You will need to create an array of character arrays (strings). Search them to convert to and integer (index into that array) and use that instead.


I'm afraid not. To compare strings/char-arrays, you have to use some other functions such as 'strcmp'. If you really want to use the switch-case structure, you can map each of your strings to distinct integers and switch by it. Here is a DEMO.


If you ask about its validity, yes it's valid and the compiler would be happy to compile. However, the compiler won't compare the content (the characters in the string), instead the pointer value would be compared.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜