Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
–
$ gcc -Wall -Wextra your_code.c
warning: format ‘%lu’ expects type ‘long unsigned int’, but argument 2 has type ‘unsigned int’
It's not a long
, don't use the l
specifier.
Your code has Undefined Behaviour, and in practice it essentially reads garabage.
–
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.