Search code examples
sizec89

C89: signed/unsigned mismatch


Are signed/unsigned mismatches necessarily bad?

Here is my program:

int main(int argc, char *argv[]) {
    unsigned int i;

    for (i = 1; i < argc; i++) { // signed/unsigned mismatch here

    }
}

argc is signed, i is not. Is this a problem?


Solution

  • "signed/unsigned mismatches" can be bad. In your question, you are asking about comparisons. When comparing two values of the same base type, but one signed and one unsigned, the signed value is converted to unsigned. So,

    int i = -1;
    unsigned int j = 10;
    
    if (i < j)
        printf("1\n");
    else
        printf("2\n");
    

    prints 2, not 1. This is because in i < j, i is converted to an unsigned int. (unsigned int)-1 is equal to UINT_MAX, a very large number. The condition thus evaluates to false, and you get to the else clause.

    For your particular example, argc is guaranteed to be non-negative, so you don't have to worry about the "mismatch".