Roman A. Taycher
Roman A. Taycher

Reputation: 19505

Is it bad practice to use -1 as an invalid value (for enums and possibly unkown values)

Is it a bad idea to use -1 as an invalid value for an enum value(for enumerations that start at 0 or greater). For uninitialized values or values that should no longer have a valid values. What about for testing how functions deal with invalid

#define INVALID_ENUM_VALUE -1

What about setting a random uint value to -1 if its in an uninitialized/invalid(say a resource id).

#define INVALID_UNINT_VALUE -1

Are there potential issues with wraparound? It's not particularly likely a valid integer will have that value if the program is not very complicated and doesn't run for a long time. Should I use UINT_MAX? Give up and just use a bool to track valid state?

Upvotes: 4

Views: 174

Answers (2)

detly
detly

Reputation: 30342

Here are the approaches I use:

  • If you're using enums, add another value for "invalid state"
  • If you have a function that returns, say, an int, either:
    • return a struct instead that has an extra field (eg. valid_result or error), or
    • take a pointer to an int that you modify for the result and have the return value report the error

Upvotes: 3

user2100815
user2100815

Reputation:

If all integers are possible good values for in code, as they are for (say) addition, then using -1 (or any numeric value) to indicate errors or unknowns doesn't make sense - you need to use some other mechanism, or simply ignore errors.

Upvotes: 4

Related Questions