Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

switch-case and char arrays

Status
Not open for further replies.

cadbilbao

Programmer
Apr 9, 2001
233
ES
Is it possible to make a switch-case with char arrays?

I am trying with this piece of code:


char *value;
...
switch (value) {
case "John":
printf("Your name is John\n");
break;
case "Tom":
printf("Hello, Tom!\n");
break;
}

But I get this error:
<<error C2450: switch expression of type 'char *' is illegal
Integral expression required >>

Any help?
 
You cannot switch on a pointer. You need to dereference it:

switch(*value){
...
}

Regards,

Charles
 
Only one problem... switch *value will only compare the first character. I would change it to if's instead

if(!strcmp(value,&quot;John&quot;)
{
...
}
else if(!strcmp(value,&quot;Tom&quot;)
{
...
}
else
{
... // default in switch
}

This could possibly be a bit big though.

Matt
 
in case statement you can use only char's(not strings or char arrays), short integers, long integers and all of them must be constants, not variables. John Fill
1c.bmp


ivfmd@mail.md
 
Cadbilbao -

Do like Zyrenthian says and use a if..elseif..else structure with strcmp, wcscmp, or _tcscmp.

Chip H.
 

You can reduce the size of such
an if...else construct with this trick.

char *names[]= {&quot;John&quot;, &quot;Dick&quot;, &quot;Harry&quot;, NULL};
char **p;

char *value=&quot;Harry&quot;;
for ( p=names; *p!=NULL; p++ )
{
if ( !strcmp(value, *p))
printf(&quot;I am %s&quot;, *p);
}


Anand
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mail me at abpillai@excite.com if you want additional help. I dont promise that I can solve your problem, but I will try my best.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top