C ++ int vs long

In C ++, is there any benefit to using long over int?

It seems that the default long word size for x86 and x86_64 architectures (32 bits on x86 and 64 bits on x86_64, and int is 32 bits on both), which (theoretically) should be faster when performing arithmetic.

The C ++ standard guarantees that sizeof (int) <= sizeof (long), but it seems that this is the default long size on both 32-bit and 64-bit systems, so you should use int instead where it is for a long time maybe when trying to write code portable across both architectures?

+6
source share
3 answers

What is faster and what is not is that it is becoming increasingly difficult to predict every day. The reason is that processors are no more β€œsimple” and with all the complex dynamics and the algorithms behind them, the final speed may follow rules that completely contradict intuition.

The only way out is to simply measure and decide. Also note that what is faster depends on small parts, and even for compatible processors, for optimization, it may be pessimization for another. For very important parts, some software simply tries and checks the timings for different approaches at runtime during program initialization.

However, as a rule, the faster integer you can get is int . You should use other integers only if you need them (for example, if long longer and you need higher precision, or if short less, but enough, and you need to save memory).

Better yet, if you need a specific size, use a fixed standard type or add a typedef instead of just sprinkling long where you need it. Thus, it will be easier to support different compilers and architectures, and it will also be clear who will read the code in the future.

+1
source

long guaranteed to be at least 32 bits, while int guaranteed to be at least 16 bits. When writing a fully portable program, you can use long , where the guaranteed int size is not enough for your needs.

In practice, however, many people make the implicit assumption that int more than standard guarantees, since they are intended only for targeting such platforms. In these situations, this is usually not a big deal.

int must be the "natural" size of the number for the system; in theory, long can be more expensive, but on many architectures, operations on long not more expensive, even if long is actually longer than int .

+5
source

If you need integer types that will be the same size across platforms, you need types in <stdint.h> .

For example, if you absolutely need an unsigned 32-bit integer, you want uint32_t . If you absolutely need a 64-bit signed integer, you want int64_t .

+4
source

Source: https://habr.com/ru/post/921459/


All Articles