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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With