Data Types in C++



In this tutorial, we will learn about data types in C++. We will cover the basics of different data types, including their usage and syntax.


What are Data Types

Data types in C++ define the type of data that a variable can hold. Each data type specifies the size and type of variable values, which determines the operations that can be performed on those values.


Types of Data Types

Here are the primary data types available in C++:

  • int: Integer type
  • float: Floating point type
  • double: Double precision floating point type
  • char: Character type
  • bool: Boolean type
  • string: String type (from the C++ Standard Library)

Syntax

The syntax to declare variables with data type in C++ is:

data_type variable_name;


Example 1: Variable with Integer data type value

  1. Declare an integer variable named num.
  2. Assign a value of 10 to the variable.
  3. Print the value of the variable.

C++ Program

#include <iostream>
int main() {
	int num = 10;
	std::cout << "The value of num is: " << num << std::endl;
	return 0;
}

Output

The value of num is: 10


Example 2: Variable with Floating Point data type value

  1. Declare a float variable named pi.
  2. Assign a value of 3.14 to the variable.
  3. Print the value of the variable.

C++ Program

#include <iostream>
int main() {
	float pi = 3.14f;
	std::cout << "The value of pi is: " << pi << std::endl;
	return 0;
}

Output

The value of pi is: 3.14


Example 3: Variable with Double data type value

  1. Declare a double variable named e.
  2. Assign a value of 2.718 to the variable.
  3. Print the value of the variable.

C++ Program

#include <iostream>
int main() {
	double e = 2.718;
	std::cout << "The value of e is: " << e << std::endl;
	return 0;
}

Output

The value of e is: 2.718


Example 4: Variable with Character data type value

  1. Declare a char variable named initial.
  2. Assign the value 'A' to the variable.
  3. Print the value of the variable.

C++ Program

#include <iostream>
int main() {
	char initial = 'A';
	std::cout << "The value of initial is: " << initial << std::endl;
	return 0;
}

Output

The value of initial is: A


Example 5: Variable with Boolean data type value

  1. Declare a boolean variable named isTrue.
  2. Assign the value true to the variable.
  3. Print the value of the variable.

C++ Program

#include <iostream>
int main() {
	bool isTrue = true;
	std::cout << "The value of isTrue is: " << std::boolalpha << isTrue << std::endl;
	return 0;
}

Output

The value of isTrue is: true


Example 6: Variable with String data type value

  1. Include the string library.
  2. Declare a string variable named name.
  3. Assign the value 'John' to the variable.
  4. Print the value of the variable.

C++ Program

#include <iostream>
#include <string>
int main() {
	std::string name = "John";
	std::cout << "The value of name is: " << name << std::endl;
	return 0;
}

Output

The value of name is: John