## Problem

## Solution

We need to calculate it manually by using bit manipulation operations.
Actually values can be found out in header file `limits.h`

.
In binary representation

- signed min -> MSB bit is 1 and rest all bits are 0.
- signed max -> MSB bit is 0 and rest all nits are 1.
- unsigned min -> It is always 0.
- unsigned max -> All bits are 1.

Implementing the above logic for different data-types we get the max and min value. Each of this max and min value can be verified against the symbolic const provided in limits.h. Now putting all the together into a program we get -.

#include <stdio.h> #include <limits.h> int main() { int char_min, char_max; int uchar_min, uchar_max; long int_min, int_max; long uint_min, uint_max; char_min = (char)(1 << (sizeof(char) * 8 - 1)); char_max = ((char)(~0 & ~char_min)); printf("char MIN is %d, char MAX is %d\n", char_min, char_max); printf("CHAR_MIN is %d, CHAR_MAX is %d\n", CHAR_MIN, CHAR_MAX); uchar_min = (unsigned char)0; uchar_max = (unsigned char)~0; printf("unsigned char MIN is %d, unsigned char MAX is %d\n", uchar_min, uchar_max); printf("UCHAR_MIN is %d, UCHAR_MAX is %d\n", 0, UCHAR_MAX); int_min = (int)(1 << (sizeof(int) * 8 - 1)); int_max = ((int)(~0 & ~int_min)); printf("int MIN is %lld, int MAX is %lld\n", int_min, int_max); printf("INT_MIN is %d, INT_MAX is %d\n", INT_MIN, INT_MAX); uint_min = (unsigned int)0; uint_max = (unsigned int)~0; printf("unsigned int MIN is %lld, unsigned int MAX is %lld\n", uint_min, uint_max); printf("UINT_MIN is %u, UINT_MAX is %u\n", 0, UINT_MAX); return 0; }

char MIN is -128, char MAX is 127 CHAR_MIN is -128, CHAR_MAX is 127 unsigned char MIN is 0, unsigned char MAX is 255 UCHAR_MIN is 0, UCHAR_MAX is 255 int MIN is -2147483648, int MAX is 2147483647 INT_MIN is -2147483648, INT_MAX is 2147483647 unsigned int MIN is 0, unsigned int MAX is 4294967295 UINT_MIN is 0, UINT_MAX is 4294967295

## Links

- Next Article - K & R : Exercise 2.2 - loop equivalent
- Previous Article - K & R : Exercise 1.24 - Rudimentary C syntax checker
- All Article - K & R Answer

## No comments :

## Post a Comment