Pointers और Memory

const Correctness

const बदलाव न करने का contract है और compiler accidental write रोकता है।

const Correctness क्या है?

const बदलाव न करने का contract है और compiler accidental write रोकता है।

Read-only data और mutable pointers सही तरह व्यक्त करें।

महत्वपूर्ण बातें

  • Pointer किसी जीवित compatible object को point करे या null हो।
  • हर owned allocation को ठीक एक बार release करें।
  • Ownership और const interfaces स्पष्ट रखें।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>

int sum(const int *values, size_t count) {
    int total = 0;
    for (size_t i = 0; i < count; ++i) total += values[i];
    return total;
}

int main(void) {
    const int values[] = {2, 4, 6};
    printf("%d\n", sum(values, 3));
    return 0;
}
अपेक्षित output
12
C++
कोड चलाएँ →
main.cpp
#include <array>
#include <iostream>

int sum(const std::array<int, 3>& values) {
    int total = 0;
    for (int value : values) total += value;
    return total;
}

int main() {
    const std::array values{2, 4, 6};
    std::cout << sum(values) << '\n';
}
अपेक्षित output
12

C और C++ की तुलना

Pointer-to-const value बचाता है; const pointer address नहीं बदलता। C++ में const member functions भी हैं।

C

Ownership और cleanup programmer द्वारा लागू conventions हैं।

C++

Containers और RAII ownership को object lifetime से जोड़ते हैं।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • Null और allocation failure paths test करें।
  • AddressSanitizer और UndefinedBehaviorSanitizer चलाएँ।
  • हर pointer का ownership लिखें।