in Programming in C retagged by
984 views
9 votes
9 votes

What will be the output of the following C program?

Assume that negative numbers are represented using $2’s$ complement.

#include<stdio.h>
void main()
{
    int a = 2;
    a = ~a+2 << 1;
    printf("%d",a);
}
in Programming in C retagged by
984 views

3 Comments

2
2

@Lakshman Patel RJIT sir Is this statement is correct “The left shift and right shift operators should not be used for negative numbers. The result is undefined behavior if any of the operands is a negative number. For example results of both 1 >> -1 and 1 << -1 is undefined.” ? if yes then how we can get answer as -2?

0
0
If it is left shift then it's not a problem but in case of right shift it depends on the system hence it should be specified whether right shift is signed or unsigned.
3
3

3 Answers

6 votes
6 votes
-2 is Ans.

a = 2 (0000 0010)

precedence order : ~  then + then <<

~a=-3(1111 1101)

~a+2=-3 +2 =-1(1111 1111)

~a+2 « 1 =Left Shift = 1111 1110(Last bit will be 0)

1111 1110 is -2.
edited by

4 Comments

a= 2  = (00000010) then to store ~2(11111101) (negative no) first take 2’s complement of it which is 00000011=3

then store negative value of it so it will store -3 in a.
0
0

Here in question it is mentioned that

negative numbers are represented in 2’s complement

so don’t we have to represent (-1) in 2’s complement first? 

OR is it like they are just stored in the machine in 2's complement form and all the operations are to be performed on the resultant negative values only?

0
0

@Pranavpurkar 

Every operation is by default stored in 2’s complement form. So we perform the operation accordingly.

0
0
0 votes
0 votes

As , we have given a=2

Now what is ~a ?

it is the Bit-wise NOT operator(~) which gives the complement .

so here ~a =  -(a+1)  

i.e         ~a =   -(3)

now,

 ~a + 2 = -3 + 2 = (-1)

AS ,it is given in question that all the negative numbers are stored in 2’s complement representation

so 2’s complement of  (-1)  is 

(1111 1111)  which is  (255)  in decimal notation.

moving further,

now we have to do left shift on 255. 

[255 « 1]

which is nothing but  255 * 2^1 = 510

so in binary ( 1111 1110)

for the final output we have to again take 2’s complement of 510

which is (0000 0010)  and  (2) in decimal notation.

and as the MSB is 1[in binary notation of 510] thus negative sign must be present.

hence ,

ANS = (-2)

 

0 votes
0 votes

Answer:-2

As we know that ~a+1=-a ,

Rewrite statement a=~a+2<<1; a=~a+1+1  [~a+1=-a]

-a+1<<1;

-2+1<<1

-2

Answer:

Related questions