C++ - Data Types

In C++, there are several basic data types that you can use to store different kinds of values. Let's explore the commonly used basic data types:

Numeric Types:

  • int: Used to store integers, such as 1, -5, 100, etc.
  • float: Used to store floating-point numbers (decimal numbers), such as 3.14, -2.5, etc.
  • double: Similar to float, but with a higher precision and range.
  • char: Used to store single characters, such as 'a', '5', '@', etc.

Boolean Types:

  • bool: Used to store boolean values, which can be either true or false.

Character Types:

  • char: Used to store individual characters. It can hold any character from the ASCII character set, such as 'a', 'A', '7', '#', etc.
  • wchar_t: Used to store wide characters, which can represent a broader range of characters, including those beyond the ASCII set.

String Types:

  • std::string: Used to store a sequence of characters (a string). It is a part of the Standard Template Library (STL) and provides various string manipulation functions.
#include <iostream>
#include <string>
int main() {
    int age = 25;
    float weight = 65.5;
    double pi = 3.14159;
    char grade = 'A';
    bool isStudent = true;
    std::string name = "John Doe";
    std::cout << "Age: " << age << std::endl;
    std::cout << "Weight: " << weight << std::endl;
    std::cout << "Pi: " << pi << std::endl;
    std::cout << "Grade: " << grade << std::endl;
    std::cout << "Is student? " << isStudent << std::endl;
    std::cout << "Name: " << name << std::endl;
    return 0;
}

In this example, we declare variables of different data types (int, float, double, char, bool, and std::string) and initialize them with specific values. Then, we use std::cout to display the values of these variables on the console.

It's important to choose the appropriate data type based on the kind of data you want to store to ensure efficient memory usage and accurate representation of the values.