I would like to force a functions parameters to accept only specific definitions. For example, consider #define OUTPUT 1, #define INPUT 0 and void restrictedFunction(int parameter); .
How would I force restrictedFunction(int parameter) to accept only OUTPUT or INPUT?
I would also like to take into consideration that another definition may have the same value, for example, #define LEFT 1 and #define RIGHT 0.
So in this case I would like restrictedFunction(int parameter) to be able to accept only OUTPUT and INPUT specifically.
It doesn’t absolutely force the use of the values (the compiler will let someone write
restrictedFunction(4)), but it is about as good as you’ll get.If you truly want to force the correct type, then:
In C99 or later, you could call that with:
This is a compound literal, creating a structure on the fly. It is not entirely clear that the structure type really buys you very much, but it will force the users to think a little and may improve the diagnostics from the compiler when they use it wrong (but they can probably use
restrictedFunction((IO_Param){ 4 });still).What this means is that your
restrictedFunction()code should be ready to validate the argument: