Ajit Jose Sylvester
Ajit Jose Sylvester

Reputation: 43

Is there any way I can restrict the values which can be take as cases in a switch statement?

Is there any way in which I can restrict the values which can be taken as cases in a switch statement?

Say, for example, I have this code in C

#include "stdio.h"
#include "stdlib.h"

#define FRIDAY    (5)

typedef enum {  
    SUNDAY, 
    MONDAY, 
    TUESDAY, 
    WEDNESDAY, 
    THURSDAY 
}e_case_values;

int main()
{
    e_case_values case_value = SUNDAY;

    switch(case_value)
    {
        case SUNDAY:
            printf("The day is Sunday");
        break;

        case MONDAY:
            printf("The day is Monday");

        case FRIDAY:
            printf("The day is Friday");

        default:
            printf("Some odd day");
    }

    return EXIT_SUCCESS;
}

Now, my objective is that the switch statement can only take values which are defined by the enum e_case_values and not by any other means. If the code does contain such usage, I wish to throw errors during compilation itself. Is there any way to do so?

Upvotes: 1

Views: 65

Answers (2)

user1508519
user1508519

Reputation:

The closest I can think of is enabling warnings:

main.cpp:27:9: warning: case value '5' not in enumerated type 'e_case_values' 
                        [-Wswitch]

         case FRIDAY:

Then you can do -Werror=switch to only treat this warning as an error. It won't affect other warnings. The problem of course is that you see 5 instead of FRIDAY in the error message. I didn't see #define FRIDAY (5).

Upvotes: 3

NPE
NPE

Reputation: 500585

No, there is no way to do this in C.

Upvotes: 3

Related Questions