code:
#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[]) {
printf("%lu\n%lu\n%lu\n%lu\n%lu\n%lu\n%lu\n",
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX);
return 0;
}
output:
4294967295
4294967295
4294967295
4294967295
4294967295
18446744073709551615
18446744073709551615
bug or intentional? and why? i think it speaks for itself but the interface needs me to add more lines before i can post it (to much code for to less text lol)
You are using %lu
, this is incorrect. The %lu
specifier is for unsigned long
and only unsigned long
, not uint32_t
. This is why the output is incorrect. Use PRIu32
instead.
Your compiler should have caught this error for you, if you were compiling with warnings enabled.
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h> // defines PRIu32
printf(
"%" PRIu32 "\n"
"%" PRIu32 "\n"
"%" PRIu32 "\n"
"%" PRIu32 "\n"
"%" PRIu32 "\n"
"%" PRIu32 "\n"
"%" PRIu32 "\n",
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX);
In practice, PRIu32
is defined to "u"
on most systems.
This is undefined behavior: you are passing unsigned int
, but your %lu
format tells printf
that you are passing long unsigned int
. This leads to undefined behavior, because printf
goes by what the format specifier says (in fact, it has no other way to find out, because type information is not passed to printf
).
Once you fix your format issue, the problem goes away:
printf("%u\n%u\n%u\n%u\n%u\n%u\n%u\n",
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX,
UINT32_MAX);
This prints
4294967295
4294967295
4294967295
4294967295
4294967295
4294967295
4294967295
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With