int main(void) { // your code goes here unsigned int i = 2...">

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?

+6
source share
1 answer

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 char value is assigned an int value with the same value of -23 .
  • the comparison must be performed on int and unsigned int , the general type is unsigned int , as defined in the C standard.
  • int converts to unsigned int with value UINT_MAX - 23 , a very large number.
  • Comparison is performed using unsigned int values: 23 is the lower value, comparison is false.
  • The else branch is else , no is 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

+11
source

All Articles