Why does this not work as expected?
int main()
{
unsigned char louise, peter;
printf("Age of Louise: ");
scanf("%u", &louise);
printf("Age of Peter: ");
scanf("%u", &peter);
printf("Louise: %u\n", louise);
printf("Peter: %u\n", peter);
return 0;
}
Outputs:
Age of Louise: 12
Age of Peter: 13
Louise: 0
Peter: 13
But if I swap variable declarations it works:
unsigned char peter, louise;
Outputs:
Age of Louise: 12
Age of Peter: 13
Louise: 12
Peter: 13
I’ve also noticed that using int or unsigned int works without needing to swap variables, but chardoesn’t.
I’ve tried putting printf("%u", louise); just after the scanf() for louise and the value is saved correctly. And if I comment out the second scanf() it also works fine…
The “problem” shows on Windows (DevCpp) and Linux (kwrite + make). Is that a bug of the compiler, or mine?
That is your bug, your variables were of type
unsigned charwhich is 1 byte, however, you entered 12 which is 4 bytes (a unsigned int), that caused an overflow (implementation defined by the compiler/runtime), and that would explain it overwriting the next variable in memory. You used the%uspecifier forprintfwhich is anunsigned int, for aunsigned charvariable, that is incorrect and does not match up. That explains, as you have discovered yourself, that using anunsigned intorintworks, as there was sufficient room to hold the values on input.Hope this helps,
Best regards,
Tom.