Search code examples
cgccsetswitch-statementc89

C89 Switch case using a set


I'm trying to write a fuction which checks whether an input is a valid double value. since I recently learned about the switch/case/default feature I wanted to use it to solve the problem

switch(carrier[i]){
        case ("+" || "-") :  //case 1
            if(kvcase == closed){
                printf("Error! Invaled input\n");
            }
            else /*save sign and close case*/
                break;

        case '.' : 
            if(deccase == closed){
                printf("Error! Invaled input\n");
            }
            else /*save comma and close case*/
                break;

        case '[0-9]' :  //case 3
            break;

        case ' ':
            printf("staring with whitespace\n");
            break;

        default:
        printf("empty\n");
            break;


    }

To answer the question please igonre the resr of the code. The Question is only about the proper way to state a case.

1) is case 1 valid or do I have to seperate it into two different cases

2) is case 3 valied? I'm trying to use a set of numbers. so if char carrier[i] is a number case is matched. I know of isdigit() function, but I don't want to just get around the problem, unless it's impossible for switch case to work with a set.

Extra Info: - carrier ist of type char* and has been given a value - I'm compiling with gcc and the code needs to be in c89 standard, whatever that is.


Solution

  • The Question is only about the proper way to state a case.
    the code needs to be in c89 standard

    Only 1 constant per case in standard C. No use of // comments in C89.

    switch(carrier[i]) {
      case `+`: /* Fall through */  /*Comment not required, but good style */
      case `=`: 
        /* case 1 code here */
        break;
      case '.' : 
        if(deccase == closed) ...
        break;
      case '0' : /* Fall through */
      case '1' : /* Fall through */
      case '2' : /* Fall through */
      case '3' : /* Fall through */
      case '4' : /* Fall through */
      case '5' : /* Fall through */
      case '6' : /* Fall through */
      case '7' : /* Fall through */
      case '8' : /* Fall through */
      case '9' : 
        /* case 3 */
        ...
        break;
      case ' ':
        printf("staring with whitespace\n");
        break;
      default:
        printf("empty\n");
        break;
    }