in Programming in C retagged by
540 views
8 votes
8 votes

What is the output of the following code? Assume that int is $32$ bits, short is $16$ bits, and the representation is two’s complement.

unsigned int x = 0xDEADBEEF;
unsigned short y = 0xFFFF;
signed int z = -1;
if (x > (signed short) y)
    printf("Hello");
if (x > z)
    printf("World");
  1. Prints nothing
  2. Prints ”Hello”
  3. Prints ”World”
  4. Prints ”HelloWorld”
in Programming in C retagged by
540 views

1 comment

1
1

1 Answer

6 votes
6 votes

unsigned int x = DEADBEEF

unsigned short y = FFFF

signed int z = -1 = FFFFFFFF (bit pattern for -1)

( x > (signed short) y ) → first y is type casted to signed short, now one operand is unsigned int and other operand is signed short, so signed short is promoted to unsigned int, sign extension will happen on y, so we’re actually checking ( DEADBEEF > FFFFFFFF ). This equates to False.

( x > z) → here, one operand is unsigned int and other is signed int, so signed int is promoted to unsigned int, so we’re actually checking ( DEADBEEF > FFFFFFFF ). This equates to False.

Thus, the program will not enter in both if statements.

Answer – A

1 comment

edited by

@Deepak Poonia @Sachin Mittal 1

$( x > (signed \ short)y )$

 y will be first  typecasted to signed short then it will be promoted to UNSIGNED INT and sign extension will be performed so how do we know that sign extension will be performed according to present data type(UNSIGNED INT i.e. 0’s before the no) or last data type(signed short i.e. 1’s before the no.) 

0
0
Answer:

Related questions