Reputation: 465
I've written the following program which seems to work well for what I need to do. However, I wonder why UINT_MAX is giving me -1 in the output (via printf()) and not 4294967295, as specified here: https://www.tutorialspoint.com/c_standard_library/limits_h.htm
#include <stdio.h>
#include <limits.h>
int main () {
printf("Below is the storage size for various data types.\n\n");
//char data type
printf("**char**\nStorage size: %d byte \t Minimum value: %d \t Maximum value: %d\n\n", sizeof(char), CHAR_MIN, CHAR_MAX);
//signed char data type
printf("**signed char**\nStorage size: %d byte \t Minimum value: %d \t Maximum value: %d\n\n", sizeof(signed char), SCHAR_MIN, SCHAR_MAX);
//unsigned char data type
printf("**unsigned char**\nStorage size: %d byte \t Maximum value: %d\n\n", sizeof(unsigned char), UCHAR_MAX);
//int data type
printf("**int**\nStorage size: %d bytes \t Minimum value: %d \t Maximum value: %d\n\n", sizeof(int), INT_MIN, INT_MAX);
//unsigned int data type
printf("**unsigned int**\nStorage size: %d bytes \t Maximum value: %d\n\n", sizeof(unsigned int), UINT_MAX);
}
Am I omitting a detail or misunderstanding something?
Upvotes: 0
Views: 3028
Reputation: 3282
%d
in the format string passed to printf
means signed integer
(for more information, see this link: http://www.cplusplus.com/reference/cstdio/printf/).
You're trying to format and print a maximum value of an unsigned integer as if it was a signed integer. Because signed integer cannot hold a maximum value of an unsigned integer (most significant bit is used for sign), it overflows and get start getting negative numbers.
If you modify your example to this:
printf("**unsigned int**\nStorage size: %zu bytes \t Maximum value: %u\n\n", sizeof(unsigned int), UINT_MAX);
it will give you the result you expect.
As also pointed out by others, %zu
is the correct specifier for the result of sizeof
.
Upvotes: 6
Reputation: 67709
Because you use %d
which expects the signed int
. use %u instead.
In Two's complement the -1 binary representation is the same as UINT_MAX
Upvotes: 2