Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the warning "comparison of promoted ~unsigned with unsigned"

Tags:

c

gcc

I've encountered a warning that I don't really understand. The warning is generated by comparing what I consider to be one unsigned with another unsigned.

Here is the source:

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

int main()
{
    uint8_t *arr = malloc(8);
    assert(arr);

    /* fill arr[] with stuff */

    if (arr[3] != (uint8_t)(~arr[2])) { // Warning is here
        /* stuff */
    }
    return EXIT_SUCCESS;
}

Which I build using the following procedure:

user@linux:~ $ gcc -o test -Wall -Wextra test.c 
test.c: In function ‘main’:
test.c:13:16: warning: comparison of promoted ~unsigned with unsigned [-Wsign-compare]

I'm using gcc version 4.7.2 20121109 (Red Hat 4.7.2-8)

How can I fix the above comparison?

like image 540
Kotte Avatar asked Aug 26 '13 15:08

Kotte


2 Answers

I had the same problem and I worked around it by using an intermediate variable:

uint8_t check = ~arr[2];
if (arr[3] != check)
like image 190
strawbot Avatar answered Oct 31 '22 20:10

strawbot


Yes I think its a bug. Read [Bug c/38341] Wrong warning comparison of promoted ~unsigned with unsigned and also Why, warning: comparison between signed and unsigned integer expressions?. This might help you.

like image 4
haccks Avatar answered Oct 31 '22 20:10

haccks