Consider the following code segments, and select the correct answer regarding the value of c at the end:
Code:int main() { int a = 1; unsigned int c = ((a - 2) / 2); return 0; } int main() { int a = 1; unsigned int c = a - 2; c /= 2; return 0; }
Select one:
The value of c is different because of truncation.
The value of c is different because of overflow or underflow.
The value of c is the same in both cases.
The value of c is the same because truncation removes the effect of overflow or underflow.
The answer is the second one - I would like to understand why is it.
At the first main - we have a variable of type int so when we divide it by 2 - and we get minus 0.5 - truncation happens - which leaves us with 0.
At the second main - we assign to unsigned int a negative value - which creates some enormous number (the process of overflow or underflow - I'm not sure).
But, I have read a little about unsigned int and overflow/underflow in respect to that - for example, here: c++ - Why is unsigned integer overflow defined behavior but signed integer overflow isn't? - Stack Overflow
So what's going on here with this negative value assignment?
Thank you.