Int v / s. long in C

On my system, I get:

sizeof ( int ) = 4 sizeof ( long ) = 4 

When I checked with the C program, both int and long overflowed to a negative value after:

 a = 2147483647; a++; 

If both can represent the same range of numbers, why should I use the long keyword?

+4
source share
8 answers

int has a minimum range from -32767 to 32767, while long has a minimum range from -2147483647 to 2147483647.

If you are writing portable code that can be compiled on different C implementations, you should use long if you need this range. If you write non-portable code for one specific implementation, then you are right - it does not matter.

+7
source

Because sizeof (int) == sizeof (long) is not always true. int normaly represents the fastest size with a size of at least 2 * 8 bits. on the other hand, at least 4 * 8 bits.

+6
source

C determines the number of integer types and sets the ratio of their sizes. Basically, this suggests that sizeof (long long)> = sizeof (long)> = sizeof (int)> = sizeof (short)> = sizeof (char), and sizeof (char) == 1.

But the actual sizes are not defined and depend on the architecture in which you work. On a 32-bit PC, int and long are usually four bytes, and long long is 8 bytes. But on a 64-bit system, the length is usually 8 bytes and therefore different from int.

There is also a type called uintptr_t (and intptr_t) that are guaranteed to be the same size as data pointers.

It is important to remember that you should not assume that you can, for example, store pointer values ​​in long or int. Being portable is probably more important than you think, and it is likely that you will want to compile your code on a 64-bit system in the near future.

+5
source

I think this is more of a compiler problem these days, because computers have gone much faster and require more numbers, as they did before.

0
source

On another platform or with a different compiler, int and long may be different. If you do not plan to transfer your code to something else or use another machine, select the one you want, it will not affect.

0
source

It depends on the compiler, and you can check this: What does the C ++ standard mean for int size, long type? p>

0
source

The size of the built-in data types depends on the implementation of C, but they all have minimal ranges. Currently, int is usually 4 bytes (32 bits), since most OSs are 32-bit. Note that char will always be 1 byte.

0
source

The size of the data type depends on the compiler. Different compilers have different sizes of int and other data types.

So, if you create code that will run on a different machine, you must use long or it depends on the range of values ​​that the ta t ur variable can have.

0
source

All Articles