#include<stdio.h>
main()
{
unsigned int a=1,b=2;
printf("%d\n",a-b>=0);
getch();
}
Why does this program output "1" ?
#include<stdio.h>
main()
{
unsigned int a=1,b=2;
printf("%d\n",a-b>=0);
getch();
}
Why does this program output "1" ?
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.
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
.
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.