C doubt

  • Thread starter sangeeta chowdhary
  • Start date
S

sangeeta chowdhary

#include<stdio.h>
#include<string.h>

int main()
{
unsigned char i=0x80;
printf("%d %d\n",i<<1,sizeof(unsigned char));
return 0;
}

output of this code is 256 1

binary conversion of i is 10000000
now if shift it to left by 1,then ishould get zero,as there is only 8
bits available for i.
why i am getting 256.
range of unsigned char is from 0 to +255
 
I

Ike Naar

#include<stdio.h>
#include<string.h>

int main()
{
unsigned char i=0x80;
printf("%d %d\n",i<<1,sizeof(unsigned char));
return 0;
}

output of this code is 256 1

binary conversion of i is 10000000
now if shift it to left by 1,then ishould get zero,as there is only 8
bits available for i.
why i am getting 256.
range of unsigned char is from 0 to +255

Integral promotions.
The type of expression ``i<<1'' is, most likely, int, not unsigned char.
Just for fun, change your program as follows:

#include<stdio.h>
#include<string.h>

int main(void)
{
unsigned char i=0x80, i1;
printf("%d %lu\n", i<<1, (long unsigned) sizeof (i<<1));
i1 = i<<1;
printf("%d %lu\n", i1, (long unsigned) sizeof i1);
return 0;
}
 
K

Keith Thompson

Jonathan Leffler said:
Sangeeta,

If you have questions about C, please ask them with a meaningful subject
line, rather than just 'C doubt' each and every time. [...]
[For instance, this question could have a title such as "Why do I get
256 from left shifting an unsigned char containing 0x80?"]

Well, that's a bit long; some newsreaders show only the first N
characters of the subject line. (For mine, with my current settings,
N seems to be about 43.)

For this question, something like "left shift of unsigned char"
would be good. It's not necessary for the entire question to appear
in the subject (and if it does, it should also be repeated in the
body of the message). The subject can just be a reminder of what
the discussion is about. Note that the word "question" (or "doubt")
can usually be omitted.

Recommended reading:
<http://www.catb.org/~esr/faqs/smart-questions.html>
 
Joined
Sep 6, 2012
Messages
1
Reaction score
0
i need the explanation for this pgm execution

#include<stdio.h>

int main()
{
int n=5;
printf("n=%*d\n", n, n);
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top