Search code examples
ctypesintegerinteger-overflow

short int Integer wrap around / short int inversion in c not understood, difference between assignment and prints


The following code fragment

short int k = -32768;
printf("%d \n", -k);
k=-k;
printf("%d \n", k);

prints

32768 
-32768

I would assume that both prints are equal. Can somebody explain what the difference is and why the assignment k=-k causes a wrap around? It was hard to find a explanation online, as i don't really know what to google.


Solution

  • Well, to print a short, you need to use a length modifier.

    Change the format string to %hd.