unsigned and signed in C
-
hi, The default integer declaration assumes a signed number. But when i tried unsigned int a=-26; printf("\n%d",a); it printed "-26" only. Why?
-
hi, The default integer declaration assumes a signed number. But when i tried unsigned int a=-26; printf("\n%d",a); it printed "-26" only. Why?
Hi,
It is undefined behaviour because you have used wrong format specifier. Use %u instead of %d for unsigned int. like :
unsigned int a=-26;
printf("\n%u",a); -
Hi,
It is undefined behaviour because you have used wrong format specifier. Use %u instead of %d for unsigned int. like :
unsigned int a=-26;
printf("\n%u",a);Thanks. Is it only about the format specifier? Or some other conversion happens inside?
-
Thanks. Is it only about the format specifier? Or some other conversion happens inside?
Yes correct. If a conversion specification is invalid, the behavior is undefined.
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
-
Hi,
It is undefined behaviour because you have used wrong format specifier. Use %u instead of %d for unsigned int. like :
unsigned int a=-26;
printf("\n%u",a);No, it is most definitely NOT undefined behavior. This is exactly the behavior one should expect. The variable a has the binary value of -26 decimal, or 0xFFFFFFE6 in 32-bit hexadecimal. When it is passed to printf with a %d format specifier it will be interpreted as a signed decimal value and -26 is printed. There is nothing undefined about that. It is interpreting the variable exactly as the format specifier is defined to. It may not be what you want but it is as expected.
-
No, it is most definitely NOT undefined behavior. This is exactly the behavior one should expect. The variable a has the binary value of -26 decimal, or 0xFFFFFFE6 in 32-bit hexadecimal. When it is passed to printf with a %d format specifier it will be interpreted as a signed decimal value and -26 is printed. There is nothing undefined about that. It is interpreting the variable exactly as the format specifier is defined to. It may not be what you want but it is as expected.
Rick York wrote:
It may not be what you want but it is as expected.
:thumbsup:
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles