Reputation: 23
I want to print out an integer type variable which value is 3000000000;
So I wrote the below code then ran it, but the printed value was incorrect. I think the variable is overflowed. But I don't know why.
#include<stdio.h>
int main(void) {
unsigned int num1 = 3000000000;
printf("%d", num1);
}
As far as I know, the maximum value of unsigned integer type variable is (2^32-1 = 4,294,967,296 - 1) when the code complies on Win32 API. But the printed value is -1294967296.
I have no idea why overflow occurs in my code.
If anyone knows the reason, please let me know :)
Best regards,
Upvotes: 0
Views: 259
Reputation: 1498
use %u
not %d
For printf
:
%d
is used by:
d, i The int argument is converted to signed decimal notation.The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is 1. When 0 is printed with an explicit precision 0, the output is empty.
%u
is used by:
o, u, x, X The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) nota‐ tion. The letters abcdef are used for x conversions; the let‐ ters ABCDEF are used for X conversions. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is 1. When 0 is printed with an explicit precision 0, the output is empty.
see http://man7.org/linux/man-pages/man3/printf.3.html
Upvotes: 1