-4
 #include<stdio.h>  
 main()  
 {  
      unsigned int a=1,b=2;  
      printf("%d\n",a-b>=0);  
      getch();  
 }

Why does this program output "1" ?

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • welcome to SO. Please take more care when asking questions here. Putting code in that way in the question title insults the eye. Summarize the problem that you have with your code, first for yourself and then put it in readable from for others. – Jens Gustedt Mar 14 '15 at 19:16
  • possible duplicate of [What happens if I assign a negative value to an unsigned variable?](http://stackoverflow.com/questions/2711522/what-happens-if-i-assign-a-negative-value-to-an-unsigned-variable) – OmnipotentEntity Mar 14 '15 at 19:25

3 Answers3

3

Compile with warnings enabled, and it will become quite obvious:

unsigned.c:5:22: warning: comparison of unsigned expression >= 0 is always true
      [-Wtautological-compare]
    printf("%d\n",a-b>=0);
                  ~~~^ ~

You are subtracting two unsigned integers. Even though the subtraction would equal -1, since they are unsigned it wraps around and you get some very large value. There is no way that an unsigned integer could ever not be greater than or equal to zero.

Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
1

Quoting ANSI C 89 standard on subtraction generating a negative number using unsigned operands:

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type

So, unsigned subtraction never generates a negative number, making your condition true, and thus prints 1.

Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34
0

try to print parts of your logic expression

    printf("%u >= %u\n",a-b, 0);

and you will see why a-b>=0 is true.

petrovich
  • 251
  • 1
  • 6