C++ Variables : परिभाषा, प्रकार और उदाहरण

Variables in CPP (CPP में वेरिएबल)

Variable एक named memory location होता है जहाँ हम data store करते हैं। Program execution के दौरान variables का use values को store और manipulate करने के लिए किया जाता है।

Syntax : data_type variable_name = value;

Example 

  • int age = 21;
  • float salary = 50000.50;

Rules

  • नाम meaningful होना चाहिए
  • आरक्षित कीवर्ड (Reserved keyword) का उपयोग नहीं कर सकते
  • Case-sensitive होते हैं

Types of variables (प्रकार )

1. Local Variable (लोकल वेरिएबल्स)

लोकल वेरिएबल्स वो होता है जो किसी function या block के अंदर बनाया गया हो।
Scope : सिर्फ उसी function/block में।

उदाहरण :

#include <iostream>
using namespace std;

void showAge() {
int age = 25; // Local variable
cout << “Age inside function: ” << age << endl;
}

int main() {
showAge();
// cout << age; // Error! main function में age नहीं दिखेगा
return 0;
}

Important:

  • Function खत्म होते ही memory free हो जाती है।
  • Function के बाहर access नहीं किया जा सकता।

2. Global Variable (ग्लोबल वेरिएबल्स)

ग्लोबल वेरिएबल्स वह variable है जो सभी functions के बाहर declare किया जाता है।
Scope: पूरे program में।

उदाहरण :

#include <iostream>
using namespace std;

int age = 30; // Global variable

void showAge() {
cout << “Age inside function: ” << age << endl;
}

int main() {
cout << “Age in main: ” << age << endl;
showAge();
return 0;
}

Important:

  • Program start होते ही memory allocate होती है।
  • Program end होते ही memory release होती है।
  • ज्यादा global variable use करना सही नहीं, क्योंकि program complex हो सकता है।
error: Content is protected !!