Signed/unsigned mismatch

314 Views Asked by At

I'm having hard time understanding nature of issue I encountered in my code. Line

if ((struct.c == 0x02) && (struct2.c == 0x02) && (struct.s == !struct2.s))
    {/**/}

where c is int and s is uint64_t produces

C4388:'==' signed/unsigned mismatch

warning. I understand what that warning is, I can't see what is triggering it here. What am I missing?

2

There are 2 best solutions below

3
On BEST ANSWER

Directly quoting the C11 standard, chapter §6.5.3.3, (emphasis mine)

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int....

So, the result of the logical ! operator is int, so !struct2.s produces int value, and the expression

....(struct.s == !struct2.s)

creates the issue.


NOTE 1:

I guess you use struct as a structure name just for illustration purpose, otherwise, struct being a reserved keyword in C you cannot use that as a variable name.


NOTE 2:

Maybe what you actually meant is (struct.s != struct2.s), but that's also just a (probable)guess.


FOOTNOTE :: Earlier question tagged C++ also, Moving it as footnote but keeping the info just for reference.
Regarding C++, the return type of ! is bool. Ref: C++11, chapter § 5.3.3 (again, emphasis mine)

The operand of the logical negation operator ! is contextually converted to bool(Clause 4); its value istrueif the converted operand isfalseand false otherwise. The type of the result is bool.

0
On

[too long for a comment]

To get the most out of compiler warnings, always try to put only one statement/expression on one line (at least temporarily when trying to determine the error's/warning's source).

So if you'd have set the code this way:

if (
    (struct.c == 0x02) 
    && (struct2.c == 0x02) 
    && (struct.s == !struct2.s)
  )

You'd been pointed by the compiler to exactly the (relativly) 4th line.