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 not, could it be true for a POSIX based OS?
Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.
long and long long are both 8 bytes.
The standards say nothing regarding the exact size of any integer types aside from char
. Typically, long
is 32-bit on 32-bit systems and 64-bit on 64-bit systems.
The standard does however specify a minimum size. From section 5.2.4.2.1 of the C Standard:
1 The values given below shall be replaced by constant expressions suitable for use in
#if
preprocessing directives. Moreover, except forCHAR_BIT
andMB_LEN_MAX
, the following shall be replaced by expressions that have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign....
minimum value for an object of type
long int
LONG_MIN
-2147483647 // −(2^31−1)maximum value for an object of type
long int
LONG_MAX
+2147483647 // 2^31−1
This says that a long int
must be a minimum of 32 bits, but may be larger. On a machine where CHAR_BIT
is 8, this gives a minimum byte size of 4. However on machine with e.g. CHAR_BIT
equal to 16, a long int
could be 2 bytes long.
Here's a real-world example. For the following code:
#include <stdio.h> int main () { printf("sizeof(long) = %zu\n", sizeof(long)); return 0; }
Output on Debian 7 i686:
sizeof(long) = 4
Output on CentOS 7 x64:
sizeof(long) = 8
So no, you can't make any assumptions on size. If you need a type of a specific size, you can use the types defined in stdint.h
. It defines the following types:
int8_t
: signed 8-bituint8_t
: unsigned 8-bitint16_t
: signed 16-bituint16_t
: unsigned 16-bitint32_t
: signed 32-bituint32_t
: unsigned 32-bitint64_t
: signed 64-bituint64_t
: unsigned 64-bitThe stdint.h
header is described in section 7.20 of the standard, with exact width types in section 7.20.1.1. The standard states that these typedefs are optional, but they exist on most implementations.
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