-1

The following code snippets although quite same but giving different answers

#include <stdio.h>
int main() {
  signed char c = -128;
  c = -c;
  printf("%d", c);.  //-128
  return 0;
}

And:

#include <stdio.h>
int main() {
  signed char c = -128;
  printf("%d", -c);.  //expected -128 but got 128
  return 0;
}

Could printf be doing internal typecasting??

jww
  • 90,984
  • 81
  • 374
  • 818
  • 1
    In latter case, -c got promoted to `int`. – YiFei Sep 02 '18 at 15:00
  • That's probably C undefined behaviour . – sagi Sep 02 '18 at 15:00
  • 2
    Just to complement @YiFei's comment: `c = -c;` is the same as `c = (signed char)(-(int)c);` and `printf("%d\n", -c);` is the same as `printf("%d\n", -(int)c);` – pmg Sep 02 '18 at 15:05
  • Possible duplicate of [printf giving wrong output](https://stackoverflow.com/questions/19946582/printf-giving-wrong-output) – πάντα ῥεῖ Sep 02 '18 at 15:20
  • If you had eneabled all recommended warnings, your compiler would have made this clear. Note: ennabling and fixing warnings is advised before asking.. – too honest for this site Sep 02 '18 at 15:26
  • I think you are overflowing but I did not find the exact duplicate (I'm pretty sure it is out there). Or maybe promotion is the effect. In the meantime try [If char c = 0x80, why does printf(“%d\n”, c << 1) output -256?](https://stackoverflow.com/q/4001630/608639), [Printing declared char value in C](https://stackoverflow.com/q/23691891/608639), [What does “representable” mean in C11?](https://stackoverflow.com/q/25776824/608639) and [Is printing negative numbers as characters well-defined in C?](https://stackoverflow.com/q/36166698/608639). – jww Sep 02 '18 at 16:05
  • @pmg is right. -c is being typecasted back to int in the 2nd case because of the - operator. Typecasting -c back to char got me the expected output – Anand Bhararia Sep 02 '18 at 20:03

1 Answers1

1

Under/Overflow of signed types is undefined behavior, you should not rely on it.

arorias
  • 328
  • 3
  • 14