Search code examples
ccoding-style

Should you always use 'int' for numbers in C, even if they are non-negative?


I always use unsigned int for values that should never be negative. But today I noticed this situation in my code:

void CreateRequestHeader( unsigned bitsAvailable, unsigned mandatoryDataSize, 
    unsigned optionalDataSize )
{
    If ( bitsAvailable – mandatoryDataSize >= optionalDataSize ) {
        // Optional data fits, so add it to the header.
    }

    // BUG! The above includes the optional part even if
    // mandatoryDataSize > bitsAvailable.
}

Should I start using int instead of unsigned int for numbers, even if they can't be negative?


Solution

  • Should I always ...

    The answer to "Should I always ..." is almost certainly 'no', there are a lot of factors that dictate whether you should use a datatype- consistency is important.

    But, this is a highly subjective question, it's really easy to mess up unsigneds:

    for (unsigned int i = 10; i >= 0; i--);
    

    results in an infinite loop.

    This is why some style guides including Google's C++ Style Guide discourage unsigned data types.

    In my personal opinion, I haven't run into many bugs caused by these problems with unsigned data types — I'd say use assertions to check your code and use them judiciously (and less when you're performing arithmetic).