Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C89: signed/unsigned mismatch

Tags:

size

c89

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?

like image 240
Nick Heiner Avatar asked Feb 14 '10 20:02

Nick Heiner


3 Answers

"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".

like image 101
Alok Singhal Avatar answered Nov 18 '22 12:11

Alok Singhal


It is not a real problem in your particular case, but the compiler can't know that argc will always have values that will not cause any problems.

like image 1
Ofir Avatar answered Nov 18 '22 13:11

Ofir


Its not bad. I'd fix compiler warnings concerning signed/unsigned mismatch because bad things can happen even if they are unlikely or impossible. When you do have to fix a bug because of signed/unsigned mismatch the compiler is basically saying "I told you so". Don't ignore the warning its there for a reason.

like image 1
void Avatar answered Nov 18 '22 13:11

void