What's the 'long' data type used for?

耗尽温柔 提交于 2019-12-03 02:16:29

It is compiler dependent. My standards-fu is a bit rusty but I believe it is defined as follows:

char <= short <= int <= long <= long long

where:

char      >= 8 bits
short     >= 16 bits
int       >= 16 bits
long      >= 32 bits
long long >= 64 bits

Which means that it is perfectly valid to have char = short = int = long = long long = 64bits and in fact compilers of some DSPs are designed that way.


This underscores the importance of actually reading your compiler documentation.

I noticed stuff called "long int" or even "long long"! Is it a data type or a modifier?

long int is the same as long (just as short int is the same as short).

long long is a distinct data type introduced by several compilers and adopted by C++0x.

Note that there is no such thing as long long long:

error: 'long long long' is too long for GCC

From one of the answers in the question you linked:

The long must be at least the same size as an int, and possibly, but not necessarily, longer.

I can't think of a better way to explain it.

long is guaranteed (at least) 32 bits. int is only guaranteed (at least) 16 bits. on 16- and 8-bit systems long provided range at a cost of efficiency.

cheers & hth.,

This is what the C++03 standard says (3.9.1/2) :

There are four signed integer types: “signed char”, “short int”, “int”, and “long int.” In this list, each type provides at least as much storage as those preceding it in the list.

So : sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long)

This is what the C++0x (3.9.1/2) and C99 (6.2.5/4) standards say :

There are five standard signed integer types, designated as signed char, short int, int, long int, and long long int.

  • long is synonym of long int
  • long long doesn't exist in C++03, but will in C++0x.
dan04

I googled it but I still don't know what its for. I've found pages that say its the same size and has the same range as an int. So what would be the point in using it?

I've wondered the same thing. And concluded that long is now useless.

Prior to the rise of 64-bit systems, the de facto standard for C integer types was:

  • char = (u)int8_t (Note that C predates Unicode.)
  • short = int16_t
  • int = intptr_t [until 64-bit], int_fast16_t
  • long = int32_t [until 64-bit], intmax_t [until 1999]
  • long long = int64_t or intmax_t

Today, however, long has no consistent semantics.

pythonic metaphor

If you want an integer that is guaranteed to be 32 bit or 64 bit, there are such types, e.g. int64_t. If you really want to ensure your int are of such a size, use these types instead of long, long long, etc. You'll need to include cstdint for these (stdint.h in C).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!