C++ Data Types
All variables use data-type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data it can
store. Whenever a variable is defined in C++, the compiler allocates some memory for that
variable based on the data-type with which it is declared. Every data type requires a different
amount of memory.
Data types in C++ is mainly divided into three types:
● Primitive Data Types: These data types are built-in or predefined data types and
can be used directly by the user to declare variables. example: int, char , float,
bool etc. Primitive data types available in C++ are:
○ Integer
○ Character
○ Boolean
○ Floating Point
○ Double Floating Point
○ Valueless or Void
○ Wide Character
● Derived Data Types: The data-types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types. These can be of four types
namely:
○ Function
○ Array
○ Pointer
○ Reference
● Abstract or User-Defined Data Types: These data types are defined by user
itself. Like, defining a class in C++ or a structure. C++ provides the following
user-defined datatypes:
○ Class
○ Structure
○ Union
○ Enumeration
○ Typedef defined DataType
Primitive data types available in C++.
● Integer: Keyword used for integer data types is i nt. Integers typically requires 4
bytes of memory space and ranges from -2147483648 to 2147483647.
● Character: Character data type is used for storing characters. Keyword used for
character data type is c
har. Characters typically requires 1 byte of memory
space and ranges from -128 to 127 or 0 to 255.
● Boolean: Boolean data type is used for storing boolean or logical values. A
boolean variable can store either true o
r false. Keyword used for boolean data
type is bool.
● Floating Point: Floating Point data type is used for storing single precision
floating point values or decimal values. Keyword used for floating point data
type is float. Float variables typically requires 4 byte of memory space.
● Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Keyword used for double
floating point data type is double. Double variables typically requires 8 byte of
memory space.
● void: Void means without any value. void datatype represents a valueless entity.
Void data type is used for those function which does not returns a value.
● Wide Character: Wide character data type is also a character data type but this
data type has size greater than the normal 8-bit datatype. Represented by
wchar_t. It is generally 2 or 4 bytes long.
Datatype Modifiers
As the name implies, datatype modifiers are used with the built-in data types to modify the
length of data that a particular data type can hold.
Data type modifiers available in C++ are:
● Signed
● Unsigned
● Short
● Long
Below table summarizes the modified size and range of built-in datatypes when combined
with the type modifiers:
DATA TYPE SIZE (IN BYTES) RANGE
short int 2 -32,768 to 32,767
unsigned short int 2 0 to 65,535
unsigned int 4 0 to 4,294,967,295
int 4 -2,147,483,648 to 2,147,483,647
long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
long long int 8 -(2^63) to (2^63)-1
unsigned long long int 8 0 to 18,446,744,073,709,551,615
signed char 1 -128 to 127
unsigned char 1 0 to 255
float 4
double 8
long double 12
wchar_t 2 or 4 1 wide character
Note : Above values may vary from compiler to compiler. In above example, we have
considered GCC 64 bit.
// C++ program to sizes of data types
#include<iostream>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char)
<< " byte" << endl;
cout << "Size of int : " << sizeof(int)
<< " bytes" << endl;
cout << "Size of short int : " << sizeof(short int)
<< " bytes" << endl;
cout << "Size of long int : " << sizeof(long int)
<< " bytes" << endl;
cout << "Size of signed long int : " << sizeof(signed long int)
<< " bytes" << endl;
cout << "Size of unsigned long int : " << sizeof(unsigned long int)
<< " bytes" << endl;
cout << "Size of float : " << sizeof(float)
<< " bytes" <<endl;
cout << "Size of double : " << sizeof(double)
<< " bytes" << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t)
<< " bytes" <<endl;
return 0;
}
Derived Data Types
The data-types that are derived from the primitive or built-in datatypes are referred to as
Derived Data Types. These can be of four types namely:
● Function
● Array
● Pointers
● References
1. Function: A function is a block of code or program-segment that is defined to
perform a specific well-defined task. A function is generally defined to save the
user from writing the same lines of code again and again for the same input. All
the lines of code are put together inside a single function and this can be called
anywhere required. main() is a default function that is defined in every program
of C++.
Syntax:
FunctionType FunctionName(parameters)
// C++ program to demonstrate
// Function Derived Type
#include <iostream>
using namespace std;
// max here is a function derived type
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
int main()
{
int a = 10, b = 20;
int m = max(a, b); // Calling above function to find max of 'a' and 'b'
cout << "m is " << m;
return 0;
}
Output:
m is 20
2. Array: An array is a collection of items stored at continuous memory locations. The idea
of array is to represent many instances in one variable.
Syntax:
DataType ArrayName[size_of_array];
Example:
// C++ program to demonstrate
// Array Derived Type
#include <iostream>
using namespace std;
int main()
{
// Array Derived Type
int arr[5];
arr[0] = 5;
arr[2] = -10;
// this is same as arr[1] = 2
arr[3 / 2] = 2;
arr[3] = arr[0];
cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3];
return 0;
}
Output:
5 2 -10 5
3. Pointers: Pointers are symbolic representation of addresses. They enable
programs to simulate call-by-reference as well as to create and manipulate dynamic
data structures. It’s general declaration in C/C++ has the format:
Syntax:
datatype *var_name;
Example:
int *ptr; // ptr points to an address which holds int data
Example:
// C++ program to illustrate
// Pointers Derived Type
void show()
{
int var = 20;
// Pointers Derived Type
// declare pointer variable
int* ptr;
// note that data type of ptr
// and var must be same
ptr = &var;
// assign the address of a variable
// to a pointer
cout << "Value at ptr = "
<< ptr << "\n";
cout << "Value at var = "
<< var << "\n";
cout << "Value at *ptr = "
<< *ptr << "\n";
}
int main()
{
show();
}
Output:
Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
Value at *ptr = 20
4. Reference: When a variable is declared as reference, it becomes an alternative
name for an existing variable. A variable can be declared as reference by putting ‘&’ in
the declaration.
Example:
// C++ program to illustrate
// Reference Derived Type
int main()
{
int x = 10;
// Reference Derived Type
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
ref = 20;
cout << "x = " << x << endl;
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << endl;
return 0;
}
Output:
x = 20
ref = 30
User-Defined DataTypes:
The data types that are defined by the user are called the derived datatype or user-defined
derived data type.
These types include:
● Class
● Structure
● Union
● Enumeration
● Typedef defined DataType
1. Class: The building block of C++ that leads to Object-Oriented programming is a
Class. It is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an instance of
that class. A class is like a blueprint for an object.
Syntax:
Example:
// C++ program to demonstrate Class
class College
{
public: // Access specifier
string col_name; // Data Members
void printname() // Member Functions()
{
cout << "Our College Name is : " << col_name;
}
};
int main()
{
College obj1; // Declare an object of class College
obj1.col_name = "chinmayadegreecollege"; // accessing data member
obj1.printname(); // accessing member function
return 0;
}
Output:
Our College Name is : chinmayadegreecollege
2.Structure: A structure is a user defined data type in C/C++. A structure creates a
data type that can be used to group items of possibly different types into a single
type.
Syntax:
struct address {
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Example:
// C++ program to demonstrate
// Structures in C++
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
int main()
{
struct Point arr[10]; // Create an array of structures
arr[0].x = 10; // Access array members
arr[0].y = 20;
cout << arr[0].x << ", " << arr[0].y;
return 0;
}
Output:
10, 20
3.Union: Like Structures, union is a user defined data type. In union, all members
share the same memory location. For example in the following C program, both x and
y share the same location. If we change x, we can see the changes being reflected in
y.
#include <iostream>
using namespace std;
// Declaration of union is same as the structures
union test {
int x, y;
};
int main()
{
// A union variable t
union test t;
// t.y also gets value 2
t.x = 2;
cout << "After making x = 2:"
<< endl
<< "x = " << t.x
<< ", y = " << t.y
<< endl;
// t.x is also updated to 10
t.y = 10;
cout << "After making Y = 10:"
<< endl
<< "x = " << t.x
<< ", y = " << t.y
<< endl;
return 0;
}
Output:
After making x = 2:
x = 2, y = 2
After making Y = 10:
x = 10, y = 10
4. Enumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};
// Program to demonstrate working
// of enum in C++
#include <iostream>
using namespace std;
enum week { Mon,
Tue,
Wed,
Thur,
Fri,
Sat,
Sun };
int main()
{
enum week day;
day = Wed;
cout << day;
return 0;
}
Output:
2
5.Typedef : C++ allows you to define explicitly new data type names by using the
keyword typedef. Using typedef does not actually create a new data class, rather it
defines a name for an existing type. This can increase the portability(the ability of a
program to be used across different types of machines; i.e., mini, mainframe, micro,
etc; without much changes into the code)of a program as only the typedef
statements would have to be changed. Using typedef one can also aid in
self-documenting code by allowing descriptive names for the standard data types.
Syntax:
typedef type name;
where t ype is any C++ data type and name is the new name for this data type.
This defines another name for the standard type of C++.
Example:
// C++ program to demonstrate typedef
#include <iostream>
using namespace std;
// After this line BYTE can be used
// in place of unsigned char
typedef unsigned char BYTE;
int main()
{
BYTE b1, b2;
b1 = 'c';
cout << " " << b1;
return 0;
}
Basic Input / Output in C++
C++ comes with libraries which provides us with many ways for performing input and
output. In C++ input and output is performed in the form of a sequence of bytes or more
commonly known as streams.
● Input Stream: If the direction of flow of bytes is from the device(for example,
Keyboard) to the main memory then this process is called input.
● Output Stream: If the direction of flow of bytes is opposite, i.e. from main
memory to device( display screen ) then this process is called output.
Header files available in C++ for Input/Output operations are:
1. iostream: iostream stands for standard input-output stream. This header file
contains definitions to objects like cin, cout, cerr etc.
2. iomanip: iomanip stands for input output manipulators. The methods declared
in this files are used for manipulating streams. This file contains definitions of
setw, setprecision etc.
3. fstream: This header file mainly describes the file stream. This header file is
used to handle the data being read from a file as input or data being written into
the file as output.
The two keywords cout in C++ and cin in C++ are used very often for printing outputs and
taking inputs respectively. These two are the most basic methods of taking input and
printing output in C++. To use cin and cout in C++ one must include the header file iostream
in the program.
We have discussed the objects defined in the header file iostream like the cin and cout.
1. Standard output stream (cout): Usually the standard output device is the display
screen. The C++ cout statement is the instance of the ostream class. It is used
to produce output on the standard output device which is usually the display
screen. The data needed to be displayed on the screen is inserted in the
standard output stream (cout) using the insertion operator(<<).
#include <iostream>
int main()
{
char sample[] = "chinmayadegreecollege";
cout << sample << " - A best institute for computer science learning";
return 0;
}
Output:
chinmayadegreecollege- A best institute for computer science learning
In the above program the insertion operator(<<) inserts the value of the string variable
sample followed by the string “A best institute for computer science learning” in the
standard output stream cout which is then displayed on screen.
2.standard input stream (cin): Usually the input device in a computer is the keyboard.
C++ cin statement is the instance of the class istream and is used to read input from
the standard input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The
extraction operator extracts the data from the object cin which is entered using the
keyboard.
#include <iostream>
using namespace std;
int main()
{
int age;
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is: " << age;
return 0;
}
Input :
18
Output:
Enter your age:
1. Your age is: 18
The above program asks the user to input the age. The object cin is connected
to the input device. The age entered by the user is extracted from cin using the
extraction operator(>>) and the extracted data is then stored in the variable age
present on the right side of the extraction operator.
3.Un-buffered standard error stream (cerr): The C++ cerr is the standard error
stream which is used to output the errors. This is also an instance of the ostream
class. As cerr in C++ is un-buffered so it is used when one needs to display the error
message immediately. It does not have any buffer to store the error message and
display later.
#include <iostream>
using namespace std;
int main()
{
cerr << "An error occured";
return 0;
}