Is it always true that long int
(which as far as I understand is a synonym for long
) is 4
bytes?
Can I rely on that? If no
As pointed out by @delnan, POSIX implementations keep the size of long
and int
as unspecified and it often differs between 32 bit and 64 bit systems.
The length of long
is mostly hardware related (often matching the size of data registers on the CPU and sometimes other software related issues such as OS design and ABI interfacing).
To ease your mind, sizeof
isn't a function, but a compiler directive*, so your code isn't using operations when using sizeof
- it's the same as writing a number, only it's portable.
use:
sizeof(long int)
* As Dave pointed out in the comments, sizeof
will be computed at runtime when it's impossible to compute the value during compilation, such as when using variable length arrays.
Also, as pointed out in another comment, sizeof
takes into consideration the padding and alignment used by the implementation, meaning that the actual bytes in use could be different then the size in memory (this could be important when bit shifting).
If you're looking for specific byte sized variables, consider using a byte array or (I would assume to be supported) the types defined by C99 in stdint.h
- as suggested by @dbush.