edited by
1,957 views
2 votes
2 votes
#include <stdio.h>
int main() {
	unsigned char a = 5;
	a |= (1<<((sizeof(char)<<3)-1));
	char b = a;
	printf("%d %d\n",b,a);
	printf("%u %u\n",b,a);
}

If the size of a char datatype is 1 Byte, then what will be the output?

[Edited]

edited by

4 Answers

Best answer
8 votes
8 votes
#include <stdio.h>
int main() {
	unsigned char a = 5;
	a |= (1<<((sizeof(char)<<3)-1));
	char b = a;
	printf("%d %d\n",b,a);
	printf("%u\n",a);
}


  • a |= (1<<((sizeof(char)<<3)-1));
    

$a |= (1<<(1<<3)-1) = 133$ $\rightarrow$ $a =133$

  • Since, $b$ is a signed char and equal to $a$, hence value of $b\rightarrow 133 \mod\ 256 \rightarrow -123$.
  • Printf here is printing signed int values and unsigned, hence

printf("%d %d\n",b,a); // b= -123, a=133
printf("%u %u\n",b,a); // b=4294967173,a=133
selected by
1 votes
1 votes
-123,-123

133

 

a=a|=(1<<((sizeof(char)<<3)-1));

a|=(1<<((1<<3)-1));

a|=(1<<(8-1));

a|=(1<<7);

a|=128;

a=a|128;//both are in unsigned

a=133;

now,

b=a;//b=-123 it is in signed

print a,b; // a=-123(bz printing the number with signed format specifier) b=-123

print a;//a=133;
0 votes
0 votes
int main() {
	unsigned char a = 5;
	a |= (1<<((sizeof(char)<<3)-1));
	char b = a;
	printf("%d %d\n",b,a);
	printf("%u %u\n",b,a);
}

carefully ! Here unsigned is used so range will get modified from 32/64 machine to machine.

(1<<((sizeof(char)<<3)-1))

          (1<<((1<<3)-1))  ==> (1<<((8)-1)) ==> (1<<(8-1)) ==>(1<<7) so,shifting 00000001 become 10000000(128)

now, a |= (1<<((sizeof(char)<<3)-1)); //here  | sign means OR so a value is 5  a= a | 128

        a= 00000101 | 10000000 

       a=133

      now, we know 

Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255

       so, b(SIGNED INT)=a(UNSIGNED INT);

      so b=133%256; ==> b = -123;

printf("%d %d\n",b,a); //OUTPUT:- -123 133

printf("%u %u\n",b,a); //NOTE %u for unsigned use as value at address whereas for signed address so

                                          //OUTPUT:- ANY MEMORY ADDRESS  133

for more see http://code.geeksforgeeks.org/pDibZO

edited by

Related questions

0 votes
0 votes
1 answer
1
2 votes
2 votes
1 answer
2
5 votes
5 votes
1 answer
3
amrendra pal asked Aug 28, 2017
495 views
#include<stdio.h int Abc(){ static int i = 19; return i; } int main(){ for(Abc() ; Abc() ; Abc()){ printf("%d ", Abc()); } return 0; }