I am writing embedded C code for a microcontroller. The code has to be shared between three different circuit boards, and the input/output configurations are set at run time from some tables during initialization.
The microcontroller has 24 ADC channels, and I have a function that can either set or clear a pin as an ADC channel. This means that an input to the function can consist of 0 to 23 (which is set in the table) and nothing else.
I would like to put some kind of preprocessor or compiler “thing” that could identify that the function received a value other than 0-23 and throw some kind of error or warning and prevent the code from compiling in case someone put an invalid value in the table.
Does anyone have some advice on how best to do this?
On most compilers (preprocessors) you can use the
#errordirective.I.e.
The above would throw an error, and would not compile.
Then use ADC_CHANNEL as the input to your function.
Or you can make
ADC_CHANNELanenum, and defineADC_CHANNEL_0 = 0,ADC_CHANNEL_1 = 1…ADC_CHANNEL_23 = 23. Then make your function take typeADC_CHANNEL_t, or whatever you want to call it, and that way if the function is called using the enumerated type as the argument, there will be no way to use an out-of-bounds value.Example:
(You don’t technically need the
= 0,= 1, etc., since the compiler will infer that from the order. By defaultenums start at 0 and increment by 1 for each value. But defining each value manually is safer, and lets you do things like only include the 3 possible ADC channels that you might possibly use, even if they aren’t consecutive.)