c problem

S

saurabh jain

i tried to run this prog
main()
{
unsigned char m=0x80;
printf("%d",m<<1);
}

what should be the output of above prog.
 
E

Emmanuel Delahaye

saurabh jain vient de nous annoncer :
i tried to run this prog
main()
{
unsigned char m=0x80;
printf("%d",m<<1);
}

what should be the output of above prog.

Nothing sensible unless you fix it to avoid invoking undefined
behaviours.

Fixes and enhancements:

#include <stdio.h>

int main (void)
{
unsigned char m = 0x80;

printf("%u\n", (unsigned) (m << 1u));

return 0;
}

I would have said that m will be converted to an int (or unsigned int,
I'm not sure. True C-gurus will answer that), then the shift occurs.
The new value is now 0x100. This value is converted to unsigned int and
passed to printf() that displays it as an unsigned decimal value (256).

Let's test:

D:\CLC\S\SAURABH>bc proj.prj
256

Of course, it proves nothing, but it lets me a chance that the fixes
and explanation was good...
 
O

Old Wolf

Emmanuel Delahaye said:
#include <stdio.h>

int main (void)
{
unsigned char m = 0x80;
printf("%u\n", (unsigned) (m << 1u));
return 0;
}
I would have said that m will be converted to an int (or unsigned int,
I'm not sure. True C-gurus will answer that), then the shift occurs.

Converted to int if INT_MAX >= UCHAR_MAX, otherwise, to unsigned int.

Also the 'u' on '1u' makes no difference (the type of the right-hand
operand of the shift operators doesn't affect the type of the result)
 

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

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,371
Latest member
Brkaa

Latest Threads

Top