Why is the output of this C code "no"?
I came across this question.
#include <stdio.h> int main(void) { // your code goes here unsigned int i = 23; signed char c = -23; if (i > c) printf("yes"); else printf("no"); return 0; } I cannot understand why the output of this code is no .
Can someone help me understand how the comparison operator works when comparing is done between int and char in C?
You are comparing unsigned int with signed char . The semantics of such a comparison does not contradict intuition: most binary operations with signed and unsigned operands are performed in unsigned operands after converting a significant value to unsigned (if both operands are the same size after promotion). Here are the steps:
- The
signed charvalue is assigned anintvalue with the same value of-23. - the comparison must be performed on
intandunsigned int, the general type isunsigned int, as defined in the C standard. intconverts tounsigned intwith valueUINT_MAX - 23, a very large number.- Comparison is performed using
unsigned intvalues:23is the lower value, comparison is false. - The
elsebranch iselse,nois printed.
Worse, if c was defined as long , the result would depend on whether the long and int tags are the same size. On Windows, it will print no , while on 64-bit Linux, it will print yes .
Never mix values ββwith and without sign in comparison. Turn on compiler warnings to prevent such an error ( -Wall or -Weverything ). You can also make all of these warnings fatal with -Werror to completely avoid this bad code.
For complete help, read the following sections of the C (C11) standard in 6.3 Conversions :
- integer shares are explained in 6.3.1.1 booleans, symbols, and integers .
- operand conversions are described in detail in 6.3.1.8. Ordinary arithmetic conversions .
You can download the latest draft C11 standard from the working group website: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf