Parikshita
Parikshita

Reputation: 1327

Implicit Type Conversion

#include<stdio.h>
int main(void)
{ 
  signed int a=-1;
  unsigned int b=1;
  int c= a+b;
  printf("%d\n",c);

  return 0;
  }

According to the rule of Implicit type conversion, if one operand is unsigned int,the other will be converted to unsigned int and the result will be unsigned int in a binary operation. so here as b is unsigned int, a should be type casted to unsigned int.As unsigned int is always +ve , so the value of a will be 1.so c=1+1=2.But the output is 0.How ?

Upvotes: 1

Views: 2122

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279255

"a should be type casted to unsigned int. As unsigned int is always +ve , so the value of a will be 1."

Correct up to "will be", but not thereafter ;-)

The result of converting a signed integer to unsigned is specified in the standard, 6.3.1.3/2:

if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type

In other words, the negative value is converted to unsigned by taking its value modulo some power of 2, not by flipping the sign.

Upvotes: 2

Donotalo
Donotalo

Reputation: 13025

Modern machines mostly uses two's complement representation for negative numbers. When two numbers are added, if any of them is negative, it will be first converted to two's complement representation. then these two numbers will be added. So computers usually performs 1 - 1 as 1 + two's complement of (-1). This results to 0.

For 1 - 2, it is 1 + two's complement(-2). Check this program, same number, different representation:

int main()
{
    signed int a = 1;
    unsigned int b = -2;

    int c = a+b;

    printf("%d\n%u\n", c, c);

    return 0;
}

Please read about two's complement representation. You'll need that to become a programmer.

Upvotes: -1

Jerry Coffin
Jerry Coffin

Reputation: 490138

-1, when cast to unsigned will become the largest possible value for that type -- e.g. with a 32-bit unsigned, it'll be 4,294,967,295. When you add 1 to that, the value "wraps around" to 0.

Upvotes: 16

Related Questions