CPP

Variables and Data Types in C++


In C++, variables are used to store data that can be manipulated and processed by your program. Data types define the kind of data that can be stored in a variable. Let's dive into variables and common data types in C++.

Variable Declaration and Initialization

In C++, you declare variables with a data type, a name, and optional initial values. Here's an example of declaring and initializing variables:

int age;           // Declaration
age = 25;          // Initialization
double price = 19.99; // Declaration and initialization
    

In the code above, we've declared and initialized an integer variable age and a double variable price.

Common Data Types

C++ provides various data types to store different kinds of information. Some common data types include:

  • int: Integer data type to store whole numbers.
  • double: Double-precision floating-point type for decimal numbers.
  • char: Character data type to store single characters.
  • bool: Boolean data type for true or false values.
  • string: String data type for text.

Sample Code

Here's a simple example of using variables and data types in C++:

#include <iostream>
using namespace std;
int main() {
    int age = 30;
    double height = 175.5;
    char grade = 'A';
    bool isStudent = true;
    string name = `John Doe`;
    cout << `Name: ` << name << endl;
    cout << `Age: ` << age << endl;
    cout << `Height: ` << height << ` cm` << endl;
    cout << `Grade: ` << grade << endl;
    cout << `Is a Student: ` << isStudent << endl;
    return 0;
}
    

In this code, we've declared and initialized variables of different data types and printed their values using cout.

Conclusion

Variables and data types are fundamental concepts in C++. They allow you to work with different types of data in your programs. As you continue your C++ journey, you'll explore more complex data types and their usage.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.