Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

c - Usage of zd vs lu for sizeof

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
"
       ,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?

question from:https://stackoverflow.com/questions/65650987/usage-of-zd-vs-lu-for-sizeof

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

isn't the result of sizeof an unsigned long anyways?

No, it returns a size_t, and a size_t needs not be the same size as an unsigned long.

For example, in the Windows world, an unsigned long is 32 bits and a size_t is 64 bits.

I understand that %zd is the suggested way to format the sizeof result.

Not quite.

Use %zu for size_t (or %zX, %zx or %zo)
Use %zd for ssize_t

Since sizeof returns a size_t, you want %zu.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...