#include <stdio.h>

int main()
    unsigned int x=2;
    int y=-1;

        printf("x greater than y");
        printf("y greater than x");

    return 0;

এই প্রোগ্রামটি চালালে আউটপুট আসবে y greater than x। কিন্তু আমরা জানি এটি ভুুল। তাহল এই আউটপুট কেন আসে?

asked 14 Mar '15, 11:03

abdullah's gravatar image


edited 25 Feb, 17:34

Mosharraf%20Hosain's gravatar image

Mosharraf Hosain ♦

In a 32-bit Signed Integer, the rightmost 31 bits represent the value of the Integer and the left most bit represents whether it is a positive or negative number. And in 32-bit Unsigned Integer, total 32 bits represent it's value. Now, In your code, X is an unsigned int and it's binary representation in memory will be (32-bit)-

X = 00000000000000000000000000000010

And Y is a signed int, whose value is negative. So it will be stored in memory in the form of 2's complement. Like this (32-bit)-

Y = 11111111111111111111111111111111

When a signed integer compared with a unsigned integer, the compiler convert the signed int to a unsigned int. So, in that case the most significant bit of Y won't represent its sign, rather it will be part of the value. So then the value of Y will be (2^32)-1 = 4294967295, which will be bigger compared to the value of X=2.

That's why it is always safe to avoid comparing a signed number with an unsigned number.

permanent link

answered 15 Mar '15, 10:26

alavola's gravatar image


Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Question tags:


question asked: 14 Mar '15, 11:03

question was seen: 352 times

last updated: 25 Feb, 17:34