|2. Variables & Data Types
Chapter 2C++ Tutorial~1 min read

Variables & Data Types

Variables आणि Data Types

C++ strongly typed language आहे — variable declare करताना type द्यायला लागतो. Built-in types: int, float, double, char, bool. C++ 11 पासून auto keyword आला — type compiler काढतो.

Basic Data Types

Data types declaration

cpp
#include <iostream>
using namespace std;

int main() {
    // Integer types
    int    age     = 20;          // 4 bytes, -2B to +2B
    short  s       = 32000;       // 2 bytes
    long   pop     = 1400000000L; // 4/8 bytes
    long long big  = 9000000000LL;// 8 bytes

    // Floating point
    float  price   = 99.99f;      // 4 bytes, f suffix
    double pi      = 3.14159265;  // 8 bytes — more precise

    // Other
    char   grade   = 'A';         // 1 byte, single quotes
    bool   isPassed = true;       // true / false

    // auto — compiler type निवडतो (C++11)
    auto city   = "Pune";    // const char*
    auto count  = 42;        // int
    auto rating = 4.5;       // double

    cout << "Age: "    << age     << endl;
    cout << "Price: "  << price   << endl;
    cout << "Grade: "  << grade   << endl;
    cout << "Passed: " << isPassed << endl;  // 1 किंवा 0

    return 0;
}

Constants आणि Variable Naming

const, #define, naming rules

cpp
// const — value बदलता येत नाही
const float PI    = 3.14159f;
const int MAX_AGE = 150;

// #define — preprocessor constant (type नाही)
#define GRAVITY 9.8
#define APP_NAME "Tech Tatya"

// PI = 3.0;  // ❌ Error: assignment of read-only variable

cout << "PI = " << PI << endl;
cout << "Gravity = " << GRAVITY << endl;

// Naming conventions
int studentAge   = 20;   // camelCase — C++ popular
int student_age  = 20;   // snake_case — also OK
const int MAX_STUDENTS = 50;  // UPPER_CASE for constants

Type Conversion

Implicit vs explicit conversion

cpp
// Implicit (automatic) — smaller → larger
int i = 10;
double d = i;     // int → double, auto

// Explicit cast — (type)value किंवा static_cast<type>
double pi = 3.99;
int x = (int) pi;              // C-style cast → 3
int y = static_cast<int>(pi);  // C++ style cast → 3

cout << x << endl;  // 3 (decimal cut होतो)

// String to number — stoi, stod
string s = "42";
int n = stoi(s);     // string to int
double f = stod("3.14");  // string to double

// Number to string — to_string
string result = to_string(n) + " marks";

Key Points — लक्षात ठेवा

  • int, float, double, char, bool — basic types
  • auto — C++11, type compiler निवडतो
  • const — read-only variable, UPPER_CASE convention
  • static_cast<type>(val) — C++ style safe cast
  • stoi(), stod(), to_string() — string↔number conversion
0/11 chapters पूर्ण