min and max value of data type in C

2020-01-27 00:02发布

What is the function to determine the min and max possible of value of datatypes (i.e, int, char.etc) in C?

标签: c types
9条回答
孤傲高冷的网名
2楼-- · 2020-01-27 00:46

MIN and MAX values of any integer data type can be computed without using any library functions as below and same logic can be applied to other integer types short, int and long.

printf("Signed Char : MIN -> %d & Max -> %d\n", ~(char)((unsigned char)~0>>1), (char)((unsigned char)~0 >> 1));
printf("Unsigned Char : MIN -> %u & Max -> %u\n", (unsigned char)0, (unsigned char)(~0));
查看更多
啃猪蹄的小仙女
3楼-- · 2020-01-27 00:51

Look at the these pages on limits.h and float.h, which are included as part of the standard c library.

查看更多
Rolldiameter
4楼-- · 2020-01-27 00:52

You'll want to use limits.h which provides the following constants (as per the linked reference):

CHAR_BIT   = number of bits in a char
SCHAR_MIN  = minimum value for a signed char
SCHAR_MAX  = maximum value for a signed char
UCHAR_MAX  = maximum value for an unsigned char
CHAR_MIN   = minimum value for a char
CHAR_MAX   = maximum value for a char
MB_LEN_MAX = maximum multibyte length of a character accross locales
SHRT_MIN   = minimum value for a short
SHRT_MAX   = maximum value for a short
USHRT_MAX  = maximum value for an unsigned short
INT_MIN    = minimum value for an int
INT_MAX    = maximum value for an int
UINT_MAX   = maximum value for an unsigned int
LONG_MIN   = minimum value for a long
LONG_MAX   = maximum value for a long
ULONG_MAX  = maximum value for an unsigned long
LLONG_MIN  = minimum value for a long long
LLONG_MAX  = maximum value for a long long
ULLONG_MAX = maximum value for an unsigned long long

Where U*_MIN is omitted for obvious reasons (any unsigned type has a minimum value of 0).

Similarly float.h provides limits for float and double types:

-FLT_MAX = most negative value of a float
FLT_MAX  = max value of a float
-DBL_MAX = most negative value of a double
DBL_MAX  = max value of a double
-LDBL_MAX = most negative value of a long double
LDBL_MAX = max value of a long double

You should read the article on floats.h carefully, though float and double can hold the prescribed minimum and maximum values but the precision with which each type can represent data may not match what it is you're trying to store. In particular, it's difficult to store exceptionally large numbers with extremely small fractions attached. So float.h provides a number of other constants that help you to determine if a float or a double can,in fact,represent a particular number.

查看更多
登录 后发表回答