Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Why does sizeof(int) vary across different operating systems?

I wounder why size of int depends on which OS one is using ,in C & C++. It's ok if size of pointer varies, but why size of integer. If 16 bit OS sizeof(int) = 2 byte, for 32 bit sizeof(int) = 4 byte. Why so?

Thanks.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Why so?

Historical reasons.

Before the advent of the ANSI C standard and size_t in 1989, int was the type used to index into arrays. malloc took an int as its argument, strlen returned one. Thus int had to be large enough to index any array, but small enough to not cause too much overhead. For file offsets, typically a larger type such as long was typedef'd to off_t.

On the PDP-11 were C was first implemented in the early 1970s, int was as large as a processor register: 16 bits. On larger machines such as the VAX, it was widened to 32 bits to allow for larger arrays.

This convention has been largely abandoned; the C and C++ standards use size_t and ssize_t for indices and lenghts of arrays. On 64-bit platforms, often int is still 32 bits wide while size_t is 64 bits. (Many older APIs, e.g. CBLAS, still use int for indices, though.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...