0
In c++ what happens by the statement s>>a . Where s and a both are integer variables.
but when the a is printed after this statement the output is 0(only when we don't enter a value in a before this… else the output of a is value of a) I couldn't get the reason behind this 0 as the output . As output should be the garbage value in a.
2 odpowiedzi
+ 2
Just for clarification:
n >> m
its equal to
n/(2^m)
so 4>>2 == 4 /(2^2) = 1
512 >> 8 == 512 /(2^8)= 2
+ 2
Arithmetic (signed) right shift operator >> and logical/arithmetic left shift operator <<, are responsible for manipulating data in bit level. Consider the following
int a = -32;
unsigned b = 32;
unsigned shift = 3;
Now, the binary representation of a and b values in 8bit words would be as
a = 1110 0000 = -32
b = 0010 0000 = 32
Shifting the number to right causes the number gets back filled with the sign bit value (MSB) for signed types (arithmetic shifting) and filling with 0 for unsigned types (logical shifting).
a >>= shift;
Yields 1111 1100 which is -4. But
b >>= shift;
Yields 0000 0100 which is 4.
Note: Left shift is always gets back filled with zero no matter which integral type you would use as data type.