1

If I have a function that takes an enum parameter, and I pass a literal that does not represent a valid enum member, can I get the compiler to emit a warning (gcc, clang, msvc?) Example code:

typedef enum {
    GPIO_0,
    GPIO_1,
    GPIO_2,
    GPIO_3
} gpio_t;

void gpio_set(gpio_t gpionum, uint8_t value) {
    // ...
}

int main(int argc, const char** argv) {
    // I want a warning here because there is no 5 in gpio_t:
    gpio_set(5, 1);
}
jdm
  • 9,470
  • 12
  • 58
  • 110
  • No, that question is about confusing two *different* enums, which my have the same values. My question is about passing a number that is "invalid" for the wanted enum. – jdm Jul 13 '21 at 07:44
  • gcc 9.3.0 will throw a invalid conversion error for that, what compiler are you using? – rmfeldt Jul 13 '21 at 07:50
  • 1
    clang has `-Wassign-enum`, gcc doesn't seem to have any option to enable such warnings. – n. m. could be an AI Jul 13 '21 at 07:51
  • @rmfeldt [nope](https://godbolt.org/z/eE6cqc39r). – n. m. could be an AI Jul 13 '21 at 07:53
  • Thanks, `-Wassign-enum` does the trick when using clang! (and `-Wenum-conversion` can tell you if you use an entry from a different enum) – jdm Jul 13 '21 at 07:59
  • @n.1.8e9-where's-my-sharem. ah, I compiled it as c++ code. my bad. – rmfeldt Jul 13 '21 at 08:01
  • 2
    Please write an answer and mark it. – the busybee Jul 13 '21 at 08:23
  • Why is this question closed? The linked questions are about runtime behavior and the posters had questions about the behavior of the language. Only accidentially do the answers mention `-Wassign-enum`. I think posting an answer here that I accept would be better for discoverability... – jdm Jul 13 '21 at 12:41

0 Answers0