Wei Xia
Wei Xia

Reputation: 533

Variable is becoming larger, but the result is for the smallest number?

I'm studying Objective-C currently. Today, I ran into a question:

On a Mac, a short is 2-byte integer, and one bit is used to hold the sign. What is the smallest number that a short can store? What is the largest?

Below is my code, I have a question about the loop. In For Loop, x is becoming larger from 0, like 1,2,3,4,5.....,but the final result is -32768. I couldn't figure out why the result is a negative number. Same problem with the largest one.

short x;
short y;

for (x = 0; x > -1; x++) {
    continue;
}
printf("Smallest short is %d. \n",x);

for (y = 0; y < 1; y--) {
    continue;
}
printf("Largest short is %d. \n",y);

Upvotes: 2

Views: 44

Answers (2)

chux
chux

Reputation: 153358

This, unfortunately is undefined behavior. The first example of undefined behavior in the C spec is

An example of undefined behavior is the behavior on integer overflow. C11dr §3.4.3 3

Both for loops incur this undefined behavior. A smart compiler may recognized that and change for (x = 0; x > -1; x++) { continue; } into for (;;) {; }, an infinite loop or ; (nothing).

for (x = 0; x > -1; x++) {
  continue;
}
for (y = 0; y < 1; y--) {
  continue;
}

So anything is possible. Code could use the following, but that likely is not what this exercise is about.

#include <limits.h>
printf("Smallest short is %d. \n", SHRT_MIN);
printf("Largest short is %d. \n", SHRT_MAX);

Upvotes: 3

kgwong
kgwong

Reputation: 121

Because of overflow.

A signed 2-byte integer can be represented by the following 16 bits:

00000000 00000000

where the first bit is the sign bit (0 for positive, 1 for negative). When you increment, you will eventually reach 01111111 11111111 (the largest positive integer) and increment once more to get 1000000 000000 (the largest negative integer). See 2's complement on why bits are formatted in this way.

Upvotes: 0

Related Questions