skip to Main Content

In C language, is it possible to pass string as a case condition in switch case?
If possible, can AI (Artificial Intelligence) be achieved?

2

Answers


  1. The short answer is that a switch in C only accepts integer values, or something easy to cast to an integer (like a character).

    There are workarounds tough, like using a hash function or using a series of “if”.

    Concerning Artificial Intelligence, this is a vast field, that cannot be addressed with a simple switch. At least for a good result. You can have a look at expert systems as a start.

    Login or Signup to reply.
  2. Is it possible to pass string as a case condition in switch case?

    No – the switch statement only operates on integer values; case labels must be constant integral expressions. You’d have to map the string onto an integer value, either by using a hash function or a lookup table or something.

    #define MAX_LEN 80 // or however long you need
    #define HELLO_STRING some-integer-value
    #define GOODBYE_STRING some-other-integer-value
    #define NO_MAPPING 0
    
    int mapToInteger( const char * str )
    {
      int mapValue = NO_MAPPING;
    
      /**
       * logic to map string to integer
       */
      return mapValue;
    }
    
    int main( void )
    {
      char inputString[MAX_LEN];
      ...
      while ( fgets( inputString, sizeof inputString, stdin ) )
      {
        switch( mapToInteger( inputString ) ) 
        {
          case HELLO_STRING: 
            process_hello();
            break;
    
          case GOODBYE_STRING:
            process_goodbye();
            break;
    
          default:
          case NO_MAPPING:
            i_dont_understand();
            break;
        }
      }
    } 
    

    Will case or whitespace matter? In other words, should "THIS IS A TEST" and "This is a test" and "tHiS iS a TeSt" all give the same result? If so, then your mapToInteger function (or whatever you decide to call it) will have to take all that into account.

    If possible, can AI (Artificial Intelligence) be achieved?

    This is the programming equivalent of asking, “if I can use a hammer to nail two pieces of wood together, can I build an apartment complex?” Yeah, sure, but you need to do a bunch of other stuff as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search