-
-
Notifications
You must be signed in to change notification settings - Fork 135
Open
Description
types_ranges.c relies on limits.h
. Here is the direct computation way as indicated in the book.
#include <stdio.h>
/**
* K&R Exercise 2-1: Write a program to determine the ranges of char, short,
* int, and long variables, both signed and unsigned, by direct computation.
*
* This method calculates the ranges by understanding their bitwise representation
* (specifically two's complement for signed types).
*/
int main() {
printf("--- Data Type Ranges by Direct Computation ---\n\n");
// --- Character Types ---
// For any unsigned type, a bit pattern of all 1s (~0) is the maximum value.
unsigned char uchar_max = ~0;
// For a signed type, the max value has the sign bit as 0 and all other bits as 1.
// This can be calculated by shifting the unsigned max right by one.
signed char schar_max = uchar_max >> 1;
// In two's complement, the minimum value is the bitwise NOT of the max value.
signed char schar_min = ~schar_max;
printf("Signed Char: %d to %d\n", schar_min, schar_max);
printf("Unsigned Char: 0 to %u\n\n", uchar_max);
// --- Short Types ---
unsigned short ushort_max = ~0;
signed short sshort_max = ushort_max >> 1;
signed short sshort_min = ~sshort_max;
printf("Signed Short: %d to %d\n", sshort_min, sshort_max);
printf("Unsigned Short: 0 to %u\n\n", ushort_max);
// --- Int Types ---
unsigned int uint_max = ~0;
signed int sint_max = uint_max >> 1;
signed int sint_min = ~sint_max;
printf("Signed Int: %d to %d\n", sint_min, sint_max);
printf("Unsigned Int: 0 to %u\n\n", uint_max);
// --- Long Types ---
unsigned long ulong_max = ~0;
signed long slong_max = ulong_max >> 1;
signed long slong_min = ~slong_max;
printf("Signed Long: %ld to %ld\n", slong_min, slong_max);
printf("Unsigned Long: 0 to %lu\n\n", ulong_max);
// --- Long Long Types (from C99 standard) ---
unsigned long long ullong_max = ~0;
signed long long sllong_max = ullong_max >> 1;
signed long long sllong_min = ~sllong_max;
printf("Signed Long Long: %lld to %lld\n", sllong_min, sllong_max);
printf("Unsigned Long Long: 0 to %llu\n\n", ullong_max);
return 0;
}
Metadata
Metadata
Assignees
Labels
No labels