Left shifting operation on int

Viewed 158

On IndiaBix.com I came across the following question.As per my experience level(beginner in C) the output of above should be 0 (10000000 << 1 is 00000000) but it came out to be 256,after going some deeper I found that we are printing using %d which supports 4 bytes so the output is 256 instead of 0.

#include<stdio.h> 
    int main()
    {
        unsigned char i = 128;
        printf("%d \n", i << 1);
        return 0;
    }

Now Consider the following Example

#include<stdio.h>

int main()
{
    unsigned int i = 2147483648;(bit 31 = 1 and b0 to b30 are 0)
    printf("%d \n", i<<1);
    return 0;
}

When I left shift the above I get 0 as the output, As %d supports value of int the output should be 0 but when I Changed %d to %ld the output is still 0. As %ld supports values upto long int the output should not be 0.Why i am getting 0 as the output.

5 Answers
Related