I understand that %zd is the suggested way to format the sizeof result. However, I don't understand why that is necessary. For example using lu gives me the same output, and isn't the result of sizeof an unsigned long anyways? For example:
printf("Sizeof(char): %lu, Sizeof(short): %lu, Sizeof(int): %lu, Sizeof(long): %lu, Sizeof(long long): %lu, Sizeof(float): %lu, Sizeof(double): %lu, Sizeof(long double): %lu\n"
,sizeof(char), sizeof(short), sizeof(int), sizeof(long), sizeof(long long), sizeof(float), sizeof(double), sizeof(long double));
printf("Sizeof(char): %zd, Sizeof(short): %zd, Sizeof(int): %zd, Sizeof(long): %zd, Sizeof(long long): %zd, Sizeof(float): %zd, Sizeof(double): %zd, Sizeof(long double): %zd"
,sizeof(char), sizeof(short), sizeof(int), sizeof(long), sizeof(long long), sizeof(float), sizeof(double), sizeof(long double));
Sizeof(char): 1, Sizeof(short): 2, Sizeof(int): 4, Sizeof(long): 8, Sizeof(long long): 8, Sizeof(float): 4, Sizeof(double): 8, Sizeof(long double): 16
Sizeof(char): 1, Sizeof(short): 2, Sizeof(int): 4, Sizeof(long): 8, Sizeof(long long): 8, Sizeof(float): 4, Sizeof(double): 8, Sizeof(long double): 16
What's the reason or advantage of using %zd and why was that added in the first place?
sizeofis asize_t, which may or may not be the same as anunsigned long, depending on the compiler, OS, and processor that you're using. And the format specifier is%zu, sincesize_tis unsigned. - user3386109size_tsomething liketypedef size_t intortypedef size_t <something-else>depending on the platform? - carl.hiasssize_tandunsigned longandunsigned intare all 32-bit size (and they can be), it does not matter whether you use%zuor%luor%u, but the code is not portable. That's why you need to use the right specifier – so thatprintf()knows the size of the argument that is passed. All it has is a promise from the format specifier and must believe the caller passed the correct size operand. It has no other way of knowing, and is up to the programmer to match the format with the type. - Weather Vane