Reputation: 19505
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
Reputation: 30342
Here are the approaches I use:
enums
, add another value for "invalid state"int
, either:
struct
instead that has an extra field (eg. valid_result
or error
), orint
that you modify for the result and have the return value report the errorUpvotes: 3
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