CPP Variables

C++ Tutorial

💻 C++ Variables (CPP Variables)

In CPP Variables are used to store data values that can be used and changed during program execution.
Each variable has a data type, name, and value.


1️⃣ What is a Variable? ⭐

A variable is a named memory location used to store data.

Example

int age = 20;

📌

  • int → data type

  • age → variable name

  • 20 → value


2️⃣ Variable Declaration Syntax ⭐

data_type variable_name;

Example



3️⃣ Variable Initialization ⭐



4️⃣ Types of Variables in C++ ⭐⭐

🔹 Local Variable

Declared inside a function.



🔹 Global Variable

Declared outside all functions.


 


🔹 Static Variable

Retains value between function calls.


Output:

1 2 3

5️⃣ Variable Naming Rules ⚠️

✔ Must start with letter or _
✔ Cannot start with number
✔ No spaces or special characters
✔ Cannot use keywords
✔ Case-sensitive

int totalMarks; // valid
int _count; // valid
int 2num; // invalid

6️⃣ Multiple Variable Declaration ⭐

int a = 5, b = 10, c = 15;

7️⃣ Changing Variable Values ⭐


Output:

20

8️⃣ Constants vs Variables ⭐⭐

Variable


Constant



9️⃣ Scope of Variables ⭐⭐


 

Output:

20

📌 Local variable has higher priority.


🔟 Common Variable Errors ❌

❌ Using undeclared variables
❌ Wrong data type
❌ Duplicate variable names in same scope
❌ Forgetting initialization


📌 Interview Questions (CPP Variables)

Q1. What is a variable?
👉 A named memory location

Q2. Difference between local and global variable?
👉 Scope & lifetime

Q3. What is static variable?
👉 Retains value between function calls

Q4. Are variable names case-sensitive?
👉 Yes


✅ Summary

✔ Variables store data
✔ Must be declared before use
✔ Have scope & lifetime
✔ Case-sensitive
✔ Can change value unless const

You may also like...