C++ Data Types


They are used to define type of variables and contents used. Data types define the way you use storage in the programs you write.

Data types can be built in or abstract.

Built in Data Types

These are the data types which are predefined and are wired directly into the compiler. eg: int, char etc.

User defined or Abstract data types

These are the type, that user creates as a class. In C++ these are classes where as in C it was implemented by structures.


Primitive Built-in Types

C++ offer the programmer a rich assortment of built-in as well as user defined data types. Following table lists down seven basic C++ data types:

Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t

Modifiers

Several of the basic types can be modified using one or more of these type modifiers:

  • signed
  • unsigned
  • short
  • long

The following table shows the variable type, how much memory it takes to store the value in memory, and what is maximum and minimum vaue which can be stored in such type of variables.

Type Typical Bit Width Typical Range
char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int Range 0 to 65,535
signed short int Range -32768 to 32767
long int 4bytes -2,147,483,647 to 2,147,483,647
signed long int 4bytes same as long int
unsigned long int 4bytes 0 to 4,294,967,295
float 4bytes +/- 3.4e +/- 38 (~7 digits)
double 8bytes +/- 1.7e +/- 308 (~15 digits)
long double 8bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t 2 or 4 bytes 1 wide character

The sizes of variables might be different from those shown in the above table, depending on the compiler and the computer you are using.

which will produce correct size of various data types on your computer.

Example

#include<iostream>
using namespace std;
int main()
{
   cout<<"Size of char : "<<sizeof(char)<<endl;
   cout<<"Size of int : "<<sizeof(int)<<endl;
   cout <<"Size of short int : "<<sizeof(shortint)<<endl;
   cout<<"Size of long int : "<<sizeof(longint)<<endl;
   cout <<"Size of float : "<<sizeof(float)<<endl;
   cout <<"Size of double : "<<sizeof(double)<<endl;
   cout <<"Size of wchar_t : "<<sizeof(wchar_t)<<endl;
}

This example uses endl, which inserts a new-line character after every line and << operator is being used to pass multiple values out to the screen. We are also using sizeof() function to get size of various data types.

When the above code is compiled and executed, it produces the following result which can vary from machine to machine:

Output
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4

Share this article on