How do I output size_t on 32-bit and 64-bit?

Asked 2 years ago, Updated 2 years ago, 77 views

You want to print out the size_t type variable using printf.

When compiled into g++-g-Wall-Werror-ansi-pedantic using %u on 32-bit, It was printed without a problem, but it's not working because it's 64 bit %lu works at 64 bits, but is there a way to operate both 32-bit and 64-bit with just one code?

size_t x = <something>;
printf( "size = %u\n", x );

warning: format '%u' expects type 'unsigned int', but argument 2 has type 'long unsigned int' The warning goes away, as expected, if I change that to %lu.

c printf

2022-09-21 21:11

1 Answers

In the C99 standard, %z is the correct expression. Example:

size_t x = ...;
ssize_t y = ...;
printf("%zu\n", x); // output as unsigned decimal
printf("%zx\n", x); // output in hexadecimal
printf("%zd\n", y); // output as signed decimal


2022-09-21 21:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.