int64_t vs long long

Ξ February 21st, 2010 | → | ∇ Programming |

This last monday morning, a colleague enters in my office and asked for my… how should I put it… let’s say technical advise.

This time the discussion was about using int64_t and double in some deprecated code involving type casts and trunc of doubles into integers.
This discussing made me research a bit about C and C++ data types regarding integers, since somewhere along the way I listened to something like “I was told to use int64_t because long long is architecture dependent”. It struck deep.

Let’s start with some simple clarifications:

  •  int, or signed int, type must contain at least 16 bits (since the standard mandates that in must support values ranging from -32,767 to +32,767)
  •  long, or long int or signed long int, type must contain at least 32 bits (since the standard mandates that in must support values ranging from -2,147,483,647 to 2,147,483,647)
  •  long long, or long long int or signed long long int, type must contain at least 64 bits (since the standard mandates that in must support values ranging from -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807). Note that this data type was first defined by C99 standard.

Regarding int64_t, as it seems, C99 standard defines a header files called stdint.h as part of the C standard library, that contains portable definitions for integer types. Portable in the sense of explicitly stating the number of bits used to represent a given integer. The definitions are in the form of intN_t and uintN_t, for N bit integers and unsigned integers, respectively. This way the programmer can ensure that, whatever the wordsize used by the processor, the right range of values can be represented. The standard garantees that the widths for these types must be ≥ N.

However well supported by modern compilers, take notice that stdint.h is not officially in the latest C++ standard (know by C++03).

Looking again at the statement that aroused my curiosity, what is the relation between int64_t and long long?
Well, they represent the same thing in most architectures! Both int64_t and long long first got defined by C99 standard, but int64_t definition ensures that 64 bits are used for represent the integer value while with long long at least 64 bits must be used.

For example, some architectures represent long and int with the same number of bits (32 bits). The standard only requires at least N bits. :-)

 

Leave a reply


On the nightstand...


    The Art of Agile Development


    Beautiful Architecture


    Modern C++ Design


    Large Scale C++ Software Design

Personal

Friends


Interesting


Shared Readings