0

This is the problem:

int num = -16;
int div = num / sizeof(int);

The value of div is incorrect (Some big garbage value). But if I do,

int num = -16;
int intSize = sizeof(int);
int div = num / intSize;

Then it gives the correct answer. What I need to know is, why does this happen?

  • 4
    Signed versus unsigned arithmetic, when you mix unsigned numbers (like from `sizeof`) and signed number (`int`s), you convert the signed numbers into unsigned ones, with negative signed numbers ending up very large. – Xarn Jul 23 '16 at 09:18
  • @Xarn Note you only convert the signed numbers to unsigned numbers if all representable values of the unsigned type cannot fit in the signed number type domain. For example, [**see here**](http://ideone.com/M1guPy). In short, the conversion to unsigned is not absolute just because one operand is a signed type and the other unsigned type. There's more to it than that. – WhozCraig Jul 23 '16 at 09:46

0 Answers0