DEV Community

Kerimova_Manzura
Kerimova_Manzura

Posted on • Edited on

πŸ”ΉC++ Variables – Complete Guide for Beginners

🧠 What is a Variable?

A variable in C++ is a named storage location that holds a value.
Think of it like a box with a label that stores information (like numbers or text) while your program runs.


πŸ“ Syntax

dataType variableName = value;
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Example:

int age = 20;
Enter fullscreen mode Exit fullscreen mode
  • int β†’ type of data (integer)
  • age β†’ variable name
  • 20 β†’ value assigned to the variable

πŸ”Ή Common Data Types in C++

Data Type Description Example
int Integer numbers int a = 10;
float Decimal numbers float pi = 3.14;
double Larger decimal numbers double d = 5.678;
char Single characters char grade = 'A';
bool True or False bool isOn = true;
string Text (needs #include <string>) string name = "Ali";

🎯 Example Code

#include <iostream>
#include <string>
using namespace std;

int main() {
    int age = 18;
    float height = 1.75;
    char grade = 'A';
    bool passed = true;
    string name = "Ali";

    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Height: " << height << " m" << endl;
    cout << "Grade: " << grade << endl;
    cout << "Passed: " << passed << endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

πŸ” Rules for Naming Variables

βœ… Allowed:

  • Letters (a-z, A-Z)
  • Digits (0-9)
  • Underscore _

❌ Not Allowed:

  • Starting with a number (e.g., 2num)
  • Special characters (@, #, !, etc.)
  • Reserved keywords (like int, return, while)

πŸš€ Pro Tip

You can declare multiple variables of the same type on one line:

int x = 5, y = 10, z = 15;
Enter fullscreen mode Exit fullscreen mode

βœ… Summary

Concept Example
Declare int num;
Initialize num = 7;
Combined int num = 7;
Output cout << num;

Top comments (0)