CPP Tutorial



C++ VARIABLES


🔸 Variables in C++

In C++, a variable is like a container or box that stores data which can change during the program execution. Every variable has a name and a data type that defines the kind of value it can hold.

Declaring Variables

To declare a variable, you write its data type followed by the variable name:

int age;
float price;
char grade;
  

Initializing Variables

You can assign a value to a variable right when you declare it, which is called initialization:

int age = 20;
float price = 99.99;
char grade = 'B';
  

Assigning Values Later

You can also declare variables first and assign values later in the program:

int age;       // declaration
age = 25;      // assignment
  

Rules for Variable Names

  • Must start with a letter (a–z, A–Z) or underscore (_).
  • Can contain letters, digits (0–9), and underscores.
  • Cannot contain spaces or special characters.
  • Cannot be a C++ reserved keyword (like int, return, for).
  • Variable names are case-sensitive (e.g., age and Age are different).

Example Program Using Variables

#include <iostream>

using namespace std;

int main() {
  int age = 21;              // declare and initialize
  float height;              // declare
  height = 5.9;              // assign value later

  cout << "Age: " << age << endl;
  cout << "Height: " << height << " feet" << endl;

  return 0;
}
  

Summary

Variables are essential to store and manipulate data in a program. You must declare variables with a specific data type and follow naming rules to create valid variables in C++.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review