C Compiler Logo

Comparison Between Signed and Unsigned

Comparison Between Signed and Unsigned

warning
warning: comparison between signed and unsigned integer expressions

Description

The program compares signed and unsigned integers, which can lead to unexpected results due to type conversion.

Common Causes

Example of Error

Error Code

int main() {
    int signed_var = -1;
    unsigned int unsigned_var = 1;
    
    if (signed_var < unsigned_var) {
        printf("signed_var is less\n");
    } else {
        printf("unsigned_var is less\n");  // This will execute!
    }
    
    return 0;
}

Solution

Cast variables to the same type before comparing them.

Corrected Code

int main() {
    int signed_var = -1;
    unsigned int unsigned_var = 1;
    
    if ((long long)signed_var < (long long)unsigned_var) {
        printf("signed_var is less\n");  // This will execute
    } else {
        printf("unsigned_var is less\n");
    }
    
    return 0;
}

Additional Tips