ravimalik20
ravimalik20

Reputation: 77

C Program to Calculate the range of data type

I have written this program to compute the maximum and minimum values of some of the data types in C, signed data types. The problem is that it is giving correct maximum values but incorrect minimum values, although i think my logic is correct. I know that there are better and efficient ways to get the result and i have implemented those too. Just need to know where the given code is going wrong.

What i have done? I have implemented this using sizeof operator and then calculating the number of bits in the type and using that to calculate the max and min values.

Thanx in advance.......

/*
* Program to calculate the size of various data types like :
* int, long, short, char
*
* Version 3
*
* Problem with this version : Working correct only for maximum value of a
* data type.
*
* Author : Ravi Malik
*/

#include<stdio.h>

int main()
{   int i, i_prev ;
    long l, l_prev ;
    char c, c_prev ;
    short s, s_prev ;

    for( i = 0, i_prev = -1 ; i > i_prev ; i = i << 1 | 0x01 )
        i_prev = i ;

    for( l = 0, l_prev = -1 ; l > l_prev ; l = l << 1 | 0x01 )
        l_prev = l ;

    for( c = 0, c_prev = -1 ; c > c_prev ; c = c << 1 | 0x01 )
    c_prev = c ;

    for( s = 0, s_prev = -1 ; s > s_prev ; s = s << 1 | 0x01 )
    s_prev = s ;

printf("MAX_INT:%d and MIN_INT:%d\n",i_prev,i);
printf("MAX_LONG:%ld and MIN_INT:%ld\n",l_prev,l);
printf("MAX_CHAR:%d and MIN_CHAR:%d\n",c_prev,c);
printf("MAX_SHORT:%hd and MIN_SHORT:%hd\n",s_prev,s);

return 0;
}

Upvotes: 0

Views: 1323

Answers (2)

doptimusprime
doptimusprime

Reputation: 9411

-1 means all the bits are set to 1. In 2's complement, minimum value is 1 followed by zero (only for signed data types).

In your case, you are getting -1 in i, l, c or s since it contains all the ones.

Initialize them with 1 and keep left shifting 1 only (no bitwise OR).

for( i = 1, i_prev = -1 ; i > i_prev ; i = i << 1)
    i_prev = i ;

Upvotes: 2

Roy Dictus
Roy Dictus

Reputation: 33149

MIN_INT = - (MAX_INT + 1) is probably the easiest formula, once you have calculated MAX_INT correctly.

So in the case of a 32-bit signed integer, MAX_INT = +2,147,483,683, and hence MIN_INT = - (MAX_INT + 1) = -2,147,483,684.

Upvotes: 0

Related Questions