Qualcomm Interview Question
Software Engineer / Developersmain()
{
int x = -20,z1;
unsigned int y = 6,z;
z = x + y;
z1=x + y;
printf("%d %u\n",z,z);
printf("%d %u\n",z1,z1);
return 0;
}
Output:
-14 4294967282
-14 4294967282
so the output depends on the format while printing,however,z,z1 store same value
This is because of promotion rules. Unsigned int + signed int will always be unsigned int. Meaning signed type is promoted to unsigned. It will be a very large <unsigned> integer which is the answer you have given. :)
depends how you print it. if you printf("%d", z) then it is -14. if you printf("%ud", z) then it is large number around 4GB
its called 2's complement arithmetic
negative numbers are represented in their 2'complement form i.e. flip all bits and add 1
2's complement of -20 in hex (for 32 bit machine) is oxffffffea
6 in hex 0x00000006
now add 0xffffffea and 0x00000006
you get 0xfffffff2 which is -14 in 2's complement
It depends on how you interpret the result:
-14 is the same as the binary representation of 4294967282.
Depends on the type of z.
- LSK August 03, 2010If z is a signed integer, then answer is -14.
If z is an unsigned integer, then x is first "converted" into an unsigned integer and then added i.e. z will become a huge number approaching the limits of the int size i.e. near 4G.