Alex Rivera | Logout

How can I compare strings in C using a `switch` statement?

Asked 2010-10-25T13:10:09.583
118

In C there is a switch construct which enables one to execute different conditional branches of code based on an test integer value, e.g.,

int a;
/* Read the value of "a" from some source, e.g. user input */
switch (a) {
  case 100:
    // Code
    break;
  case 200:
    // Code
    break;
  default:
    // Code
    break;
}

How is it possible to obtain the same behavior (i.e. avoid the so-called "if-else ladder") for a string value, i.e., a char *?

Edit
Report

1 Answer

1

Assuming little endianness and sizeof(char) == 1, you could do that (something like this was suggested by this answer).

char* txt = "B1";
int tst = *(int*)txt;
if ((tst & 0x00FFFFFF) == '1B')
    printf("B1!\n");

It could be generalized for BE case.

answered 2010-10-25T13:29:12.250

Your Answer