Creating Variable in C++
In C++, variables are used to store and manipulate data. Here’s how you can create variables in C++:
#include <iostream>
int main() {
// Example 1: Creating an integer variable
int age;
age = 25; // Assigning a value to the variable
std::cout << "Age: " << age << std::endl;
// Example 2: Creating a floating-point variable
float temperature = 98.6; // Initializing the variable with a value
std::cout << "Temperature: " << temperature << std::endl;
// Example 3: Creating a character variable
char grade = 'A'; // Initializing the variable with a character
std::cout << "Grade: " << grade << std::endl;
// Example 4: Creating a string variable
std::string name = "Abdullah"; // Initializing the variable with a string
std::cout << "Name: " << name << std::endl;
// Example 5: Creating a boolean variable
bool isStudent = true; // Initializing the variable with a boolean value
std::cout << "Is student? " << std::boolalpha << isStudent << std::endl;
return 0;
}- The
intkeyword is used to declare an integer variable (age). - The
floatkeyword is used to declare a floating-point variable (temperature). - The
charkeyword is used to declare a character variable (grade). - The
std::stringtype is used to declare a string variable (name). - The
boolkeyword is used to declare a boolean variable (isStudent).
You can initialize a variable at the time of declaration, as shown in examples 2, 4, and 5. It’s good practice to initialize variables when possible to avoid using uninitialized values.
Get Abdullah Soomro’s stories in your inbox
Join Medium for free to get updates from this writer.
Remember that C++ is a statically typed language, meaning you need to declare the data type of a variable before using it. Also, C++ supports type inference with the auto keyword, but it's often better to explicitly specify the data type for clarity and to avoid potential issues.




