What is the correct way to use printf to print a size_t in C/C++?

In C programming, size_t is an unsigned integer type used to represent the size of objects and is commonly returned by functions like sizeof and strlen. To correctly print size_t variables, we should use the %zu format specifier instead of %d or other format specifiers.

Syntax

printf("%zu", size_t_variable);

The %zu format specifier consists of −

  • z − length modifier that specifies the argument corresponds to a size_t type
  • u − conversion specifier for unsigned decimal integer

Example 1: Basic size_t Printing

This example demonstrates the correct way to print a size_t variable −

#include <stdio.h>
#include <stddef.h>

int main() {
    size_t count = 100;
    size_t array_size = sizeof(int) * 10;
    
    printf("Count value: %zu\n", count);
    printf("Array size in bytes: %zu\n", array_size);
    
    return 0;
}
Count value: 100
Array size in bytes: 40

Example 2: Using size_t with String Functions

This example shows size_t with string length calculation −

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "TutorialsPoint";
    size_t length = strlen(str);
    size_t str_size = sizeof(str);
    
    printf("String: %s\n", str);
    printf("Length (strlen): %zu characters\n", length);
    printf("Size (sizeof): %zu bytes\n", str_size);
    
    return 0;
}
String: TutorialsPoint
Length (strlen): 14 characters
Size (sizeof): 15 bytes

Why Not Use %d?

Using %d with size_t can cause issues because −

  • %d expects a signed int, while size_t is unsigned
  • On 64-bit systems, size_t may be larger than int
  • This can lead to undefined behavior or incorrect output

Conclusion

Always use %zu format specifier when printing size_t variables in C. This ensures correct output across different platforms and avoids potential undefined behavior that can occur with incorrect format specifiers.

Updated on: 2026-03-15T10:01:32+05:30

26K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements