Finding the maximum value of a short int variable in C

I worked on exercise 2-1 K & R, the goal is to calculate the range of different types of variables, below my function to calculate the maximum value of a short intmay contain:

short int max_short(void) {
    short int i = 1, j = 0, k = 0;
    while (i > k) {
        k = i;
        if (((short int)2 * i) > (short int)0)
            i *= 2;
        else {
            j = i;
            while (i + j <= (short int)0)
                j /= 2;
            i += j;
        }
    }
    return i;
}

My problem is that the return value of this function is: -32768which is obviously wrong since I expect a positive value. I can not understand where the problem is, I used the same function (with changes in the types of variables) to calculate the maximum value that the int can contain, and it worked ...

Although the problem may be caused by comparisons within operators ifand while, consequently, type casting, this did not help ...

Any ideas what causes this? Thanks in advance!

EDIT: undefined NOT .

+4
3

, , , undefined, , . - SHRT_MAX, INT_MAX... of <limits.h>. - C, , 1989 .

, K & R C 11 , 2nd - ANSI-C - , , , C .

:

unsigned int i = -1;
// i now holds the maximum value of `unsigned int`.
+5

C, . . , "". undefined, , .

- SHRT_MAX limits.h.

, unsigned short, 2. , 0.

#include <stdio.h>
#include <limits.h>

int main()
{ 
  printf("%hd\n", SHRT_MAX); // best way

  unsigned short ushort_max = ~0u;
  short short_max = ushort_max / 2;
  printf("%hd\n", short_max);

  return 0;
}

:

, ((short int)2*i)>(short int)0, . C, * >, -, " ", . int, .

0

int

OK, here I assume that the computer will handle the behavior of integer overflow by changing to negative integers, since I believe that you assumed that it was written by this program.

which outputs 32767:

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
short int max_short(void)
{
    short int i = 1, j = 0, k = 0;
    while (i>k)
    {
        k = i;
        if (((short int)(2 * i))>(short int)0)
            i *= 2;
        else
        {
            j = i;
            while ((short int)(i + j) <= (short int)0)
                j /= 2;
            i += j;
        }
    }

    return i;
}

int main() {
    printf("%d", max_short());
    while (1);
}

2 casts added

-2
source

Source: https://habr.com/ru/post/1684468/


All Articles