0

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,

  • I use Microsoft Visual Studio 2015 Professional.
2
  • 6
    Try %u instead of %d. Commented Mar 11, 2019 at 7:18
  • %d is for signed ints. It will take whatever value it finds and interpret it as signed int and print it. Try unsigned int num1 = 0xffffffff; printf("%d", num1);. It will be more obvious. 4294967295 = 0xffffffff Commented Mar 11, 2019 at 7:26

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.