Printf redifines UINT32_MAX

the 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;
}

exit:

4294967295
4294967295
4294967295
4294967295
4294967295
18446744073709551615
18446744073709551615

mistake or intentional? and why? I think it speaks for itself, but the interface requires me to add more lines before I can publish it (for a lot of code for less text messages)

+4
source share
3 answers

You use %lu, this is wrong. The %luspecifier is intended for unsigned longand only unsigned long, not uint32_t. That is why the conclusion is wrong. Use instead PRIu32.

Your compiler should have caught this error for you if you compiled with warnings turned on.

#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, it is PRIu32defined as "u"for most systems.

+14

undefined: unsigned int, %lu printf, long unsigned int. undefined , printf , ( , printf).

, :

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);

4294967295
4294967295
4294967295
4294967295
4294967295
4294967295
4294967295

+3
$ gcc -Wall -Wextra your_code.c
warning: format ‘%lu’ expects type ‘long unsigned int’, but argument 2 has type ‘unsigned int

a long, l.

Undefined Behavior, .

+1

Source: https://habr.com/ru/post/1629181/


All Articles