3
votes

I ran the following C code on Windows 8.1 (x64) to get a better understanding of the lower and upper limits of the primitive data types but I find the output surprising.

#include <limits.h>
#include <stdio.h>

int main(void)
{
    printf("\n");
    printf("Integer types");
    printf("\n");
    printf("\n");
    printf("Signed");
    printf("\n");
    printf("\n");
    printf("signed char:          %d to %d\n", SCHAR_MIN, SCHAR_MAX);
    printf("signed short int:     %d to %d\n", SHRT_MIN, SHRT_MAX);
    printf("signed int:           %d to %d\n", INT_MIN, INT_MAX);
    printf("signed long int:      %d to %d\n", LONG_MIN, LONG_MAX);
    printf("signed long long int: %d to %d\n", LLONG_MIN, LLONG_MAX);
    printf("\n");
    printf("Unsigned");
    printf("\n");
    printf("\n");
    printf("unsigned char:          0 to %d\n", UCHAR_MAX);
    printf("unsigned short int:     0 to %d\n", USHRT_MAX);
    printf("unsigned int:           0 to %d\n", UINT_MAX);
    printf("unsigned long int:      0 to %d\n", ULONG_MAX);
    printf("unsigned long long int: 0 to %d\n", ULLONG_MAX);
    printf("\n");
    printf("Platform dependant");
    printf("\n");
    printf("\n");
    printf("char: %d to %d\n", CHAR_MIN, CHAR_MAX);
    printf("\n");

    return 0;
}

The following is the output:

Integer types

Signed

signed char: -128 to 127
signed short int: -32768 to 32767
signed int: -2147483648 to 2147483647
signed long int: -2147483648 to 2147483647
signed long long int: 0 to -1

Unsigned

unsigned char: 0 to 255
unsigned short int: 0 to 65535
unsigned int: 0 to -1
unsigned long int: 0 to -1
unsigned long long int: 0 to -1

Platform dependant

char: -128 to 127

What I didn't expect is that LLONG_MIN is 0 and LLONG_MAX is -1 and UINT_MAX, ULONG_MAX and ULLONG_MAX are -1. What is going on here?

2

2 Answers

5
votes

You are using the wrong format, %d expects int, try

printf("signed long int:      %ld to %ld\n", LONG_MIN, LONG_MAX);
printf("signed long long int: %lld to %lld\n", LLONG_MIN, LLONG_MAX);

and

printf("unsigned int:           0 to %u\n", UINT_MAX);
printf("unsigned long int:      0 to %lu\n", ULONG_MAX);
printf("unsigned long long int: 0 to %llu\n", ULLONG_MAX);
1
votes

Remember that the format code "%d" is for the type signed int. For long you have to use the prefix l, like "%ld", for long long you have to use "%lld".

For unsigned int the format code is "%u", and add prefix for unsigned short, unsigned long etc.

See e.g. this reference.


To be more precise about why you get -1 for the max value, especially for the unsigned types, is because you print them as signed values, and the values are all binary ones which is -1 in two's complement systems used by all modern systems.