Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 287
Pranit P Kothari Avatar asked Feb 17 '23 22:02

Pranit P Kothari


1 Answers

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.)

like image 54
Fred Foo Avatar answered Mar 04 '23 23:03

Fred Foo