cprintfunsigned-integerconversion-specifier

Program printing incorrect symbolic constants values


I am currently learning C and I am attempting to complete the K&R exercise 2-1. (Write a program to determine the ranges of char, short, int, and long variables, both signed and unsigned, by printing appropriate values from standard headers and by direct computation.) I have written the following code to achieve this:

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

int main() {
    printf("Unsigned Variable Ranges\n");
    printf("Unsigned char:  %d    %d\n", 0, UCHAR_MAX);
    printf("Unsigned short: %d    %d\n", 0, USHRT_MAX);
    printf("Unsigned int:   %d    %d\n", 0, UINT_MAX);
    printf("Unsigned long:  %d    %d\n", 0, ULONG_MAX);
}

My thought process through this is to use the symbolic constants found in limits.h and float.h to print the minimum and maximum values in my program. The char and short values are printing correctly, but the int and long values are printing as -1. The terminal reads:

Unsigned Variable Ranges
Unsigned char:  0    255
Unsigned short: 0    65535
Unsigned int:   0    -1
Unsigned long:  0    -1

Is this an error on my part or is this a compiler/Visual Studio error?


Solution

  • For unsigned integers you have to use the conversion specifier u instead of d. Also for the type long integer you have to use the length modifier l.

    So the calls of printf can look like

    printf("Unsigned char:  %u    %u\n", 0, UCHAR_MAX);
    printf("Unsigned short: %u    %u\n", 0, USHRT_MAX);
    printf("Unsigned int:   %u    %u\n", 0, UINT_MAX);
    printf("Unsigned long:  %d    %lu\n", 0, ULONG_MAX);
    

    For the types unsigned char and unsigned short you could also use the conversion specifier %d provided that the type int can contain all values of the unsigned types after the integer promotions of the types.