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?
CodePudding user response:
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.
CodePudding user response:
When using printf you give the format string specifies what type you are printing. %d
means integer and as both maximum value for unsigned int and the max value for unsigned long can not fit in integer it overflows and is printed as -1
.
CodePudding user response:
For the sake of argument, let's suppose that unsigned int
is four bytes wide. UINT_MAX
is going to be 0xffffffff
. However, you're printing that value as an int
(because of the %d
). As a signed integer, 0xffffffff
means -1
because of two's complement.
What you want to do is print UINT_MAX
as an unsigned int
which you can do with %u
instead of %d
. Similarly, for ULONG_MAX
, you need to use %lu
.