Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 asize_ttype -
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 −
-
%dexpects a signedint, whilesize_tis unsigned - On 64-bit systems,
size_tmay be larger thanint - 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.
Advertisements
