Originally Posted by
Kayl669
Although can you give me an example as I'm not very knowledgeable about in-built functionality.
I was thinking of something like this:
Code:
#include <stddef.h>
#include <limits.h>
#include <stdio.h>
int main(void)
{
/* Assume two's complement. */
int int_max = (int)((1U << (sizeof(int) * CHAR_BIT - 1)) - 1);
printf("Maximum value of int: %u\n", int_max);
printf("Minimum value for int: %d\n", -int_max - 1);
return 0;
}
Originally Posted by
Kayl669
Also I think CHAR_BIT is part of the limits header and my exercise tells me I should be able to both calculate the range of different variable types aswell as using <limits.h>.
You do not need CHAR_BIT if you can validly assume that there are 8 bits in a byte. The problem is, if you assume nothing, i.e., you do not know if two's complement is used (but you know that it might be one's complement or sign and magnitude instead), you do not know how many bits there are in a byte (other than a minimum of 8), and you cannot refer to anything in <limits.h>, then it might be impossible to determine the maximum and minimum values of a signed integer type without risking undefined behaviour (and possibly getting a wrong answer).
EDIT:
It looks like this macro works:
Code:
#include <stdio.h>
#define BITS_PER_BYTE 8 /* Assumption without CHAR_BIT. */
/* Assume two's complement. */
#define PRINT_RANGE(integer_type) do {\
integer_type num_max = (integer_type)((1UL << (sizeof(integer_type) * BITS_PER_BYTE - 1)) - 1);\
printf("Maximum value of " #integer_type ": %lu\n", (unsigned long)num_max);\
printf("Minimum value of " #integer_type ": %ld\n", (long)(-num_max - 1));\
} while (0)
int main(void)
{
PRINT_RANGE(signed char);
PRINT_RANGE(short);
PRINT_RANGE(int);
PRINT_RANGE(long);
return 0;
}
But it basically just boils down to finding the number of bits of the type, and then computing the maximum/minimum values with that information.