Qualifiers: read-only access aur observable effects
Const access paths samjhein, phir optional pointer, volatile, restrict aur atomic contracts revisit karein.
Is chapter mein9 sections
Kabhi code ko kisi access ke through value sirf padhni hoti hai. Kabhi access ke apne special rules hote hain. Type qualifiers in restrictions aur effects ko describe karte hain. Pehle dekhein ki qualifier declaration ke kis part par apply hota hai.
Pehle do sections abhi padhein. Optional pointer aur concurrency sections par Memory & data aur Correctness & care units ke baad laut sakte hain; yahan koi prerequisite lock nahi hai.
1. const access ko read-only banata hai
const int limit = 4; se defined object ko nayi value assign nahi kar sakte. Const-qualified lvalue ke through write language constraint violate karta hai aur diagnostic required hota hai. Qualification cast-away karna genuinely const-defined object ko writable nahi banata: usko modify karna undefined behavior hai.
Lekin mutable object ka read-only view us object ko freeze nahi karta. Agle example mein view ek pointer hai: aisi value jo existing score object designate karti hai. *view ka star designated object access karta hai. View us path se write rokta hai; mutable score ko directly change karna valid rehta hai.
int score = 10;
const int *view = &score;
score = 12;
int observed = *view;
observed 12 banta hai. Score ka ek hi object hai, frozen copy nahi. Jab function supplied data ko us parameter ke through modify kiye bina inspect kare, read-only parameter useful hai. Isse yeh promise nahi milta ki koi aur data change hi nahi kar sakta.
Intentional diagnostic: const object ko assign karna
Yeh invalid C17 hai. Iska purpose constraint samjhana hai; predictable runtime result wala program nahi.
int main(void)
{
const int limit = 4;
limit = 5;
return 0;
}
2. Read-only aur constant expression alag ideas hain
const type property hai. Integer constant expression specific translation-time rules se allowed expression hai. C17 mein ordinary const integer object ko read karna sirf initializer 4 hone se integer constant expression nahi ban jaata. Optimizer ko value pata hone se language classification nahi badalti.
C17 mein array bound ya case label ke liye chhota named integer chahiye toh enumeration constant use karein. Read-only data ke liye typed const object use karein. C23 specific initialization constraints ke saath named constant objects ke liye constexpr add karta hai; isse C, C++ nahi ban jaati aur arbitrary function calls constant expressions mein allowed nahi ho jaati. Constant expressions chapter choices explain karta hai.
3. Optional: pointer ya pointed-to type qualify karein
Pointer introduction ke baad padhein
const int *reader mein reader ko doosra object designate karwa sakte hain, lekin uske through int write nahi kar sakte. int *const fixed pointer value fix karta hai; designated mutable int phir bhi change ho sakta hai. const int *const fixed_reader dono restrictions combine karta hai.
#include <assert.h>
int main(void)
{
int first = 10;
int second = 20;
const int *reader = &first;
int *const fixed = &first;
const int *const fixed_reader = &first;
reader = &second;
*fixed = 15;
assert(*reader == 20);
assert(*fixed_reader == 15);
return 0;
}
Typedef pointer level hide kar sakta hai. Is declaration mein const IntPointer ka matlab int ka const pointer hai, const int ka pointer nahi. Type alias apne complete denoted type ko naam deta hai.
typedef int *IntPointer;
int value = 7;
const IntPointer fixed = &value;
*fixed = 8;
Value par write valid hai; fixed ko reassign karna valid nahi hota. Const, pointer members se reachable objects ko recursively freeze bhi nahi karta. int ** ko force karke const int ** mat banayein: multiple pointer levels par qualification add karne ke compatibility rules stricter hain. Nested pointer APIs se pehle types aur data interfaces revisit karein.
4. volatile observable accesses describe karta hai
volatile accesses ko special observable semantics deta hai. Exactly kya access count hota hai, implementation define karti hai. Device registers ke liye target ke documented hardware aur compiler rules follow karne honge; ordinary ISO C akeli specific address ya device protocol define nahi karti.
volatile int status = 0;
int before = status;
status = 1;
int after = status;
Yahan before 0 aur after 1 hai. Yeh local example source-level accesses illustrate karta hai; interrupt simulate ya device test nahi karta. Volatile har operation slow karne ka request, general cache-flush command, atomic increment ya thread synchronization nahi hai.
volatile sig_atomic_t flag restricted asynchronous signal-handler assignment idiom mein useful hai. Isse arbitrary library calls, general shared data access ya volatile ko thread-safety mechanism ki tarah use karne ki permission nahi milti. Signals ke apne platform aur language contracts hain.
5. Optional: restrict aur atomic access ke alag roles
Arrays, pointers aur shared state ke baad padhein
restrict scoped access contract hai. Associated execution mein relevant object modify hota hai toh uske access paths ko restricted-pointer rules follow karne chahiye. Sirf doosra pointer value exist karna automatically violation nahi; read-only aliasing ka treatment alag hai. Promise tabhi karein jab callers actual access contract satisfy kar sakein.
#include <assert.h>
#include <stddef.h>
static void double_into(size_t count,
int *restrict destination,
const int *restrict source)
{
for (size_t i = 0; i < count; ++i) {
destination[i] = 2 * source[i];
}
}
int main(void)
{
const int input[3] = { 2, 3, 4 };
int output[3] = { 0 };
double_into(3, output, input);
assert(output[0] == 4 && output[1] == 6 && output[2] == 8);
return 0;
}
Shown call distinct input/output arrays use karti hai. General function ko kam se kam count ints ke accessible regions, modified/read elements ke liye conflicting overlap ki absence, aur int mein representable doubling wale source values chahiye. Cast broken promise repair nahi karta. Deeper rules ke liye effective types aur aliasing dekhein.
Atomic support wali implementation mein _Atomic int atomic integer type deta hai. Neeche operation ek object ko indivisibly update karta hai; relaxed order unrelated ordinary data publish nahi karta. Single-thread example value change check karta hai, concurrent algorithm nahi.
#include <assert.h>
#include <stdatomic.h>
#ifdef __STDC_NO_ATOMICS__
#error This example requires atomic support
#endif
int main(void)
{
_Atomic int visits = 0;
int previous = atomic_fetch_add_explicit(&visits, 1,
memory_order_relaxed);
int current = atomic_load_explicit(&visits, memory_order_relaxed);
assert(previous == 0 && current == 1);
return 0;
}
C17/C23 mein atomic support conditional hai. Multiple objects, resource lifetime ya invariant ke operation ko complete synchronization design chahiye. Threads aur shared state dekhein; volatile ya ek atomic field us design ko certify nahi karte.
6. Thought check: kya read-only view change dekh sakta hai?
Mutable score ko const int * se view karte hain. Kya next read alag ho sakta hai?
Haan. Doosra valid access mutable object change kar sakta hai, jabki view read-only rehta hai. Threaded program mein reads/writes ko required synchronization bhi chahiye; const data races remove nahi karta. Qualification, lifetime aur synchronization alag sawaalon ke answers hain.
Sources aur aage ki reading
Primary references: WG14 N1570 6.2.4, 6.3.2.3, 6.7.3, 6.7.8, 7.14.1.1, and 7.17; WG14 N3096 (C23 notes). These are public committee drafts; the examples here use a C17 baseline.
Aage badhne se pehle
- Qualifiers declaration ke particular types aur access paths par apply hote hain.
- const access us path se modification restrict karta hai; mutable target ke saare aliases freeze nahi hote.
- volatile, restrict aur atomic facilities ke specific aur different contracts hain.
In ideas ko alag rakhein
- const pointer / Pointer to const
- Ek pointer object ko nonmodifiable banata hai; doosra us access se target modify karna restrict karta hai.
Pointer declaration mein const kis part ko qualify karta hai, yeh pehchaanne ke liye kya dekhenge?
Optional: bolkar samjhein ya note rakhein. Tayyar hon toh aage badh sakte hain.Apni understanding check karein
Optional hai. Answers save ya send nahi hote; chapter kabhi lock nahi hota.
Har choice ki explanation padhein
- Nahi. Yeh access path read-only hai, par doosra permitted access original object badal sakta hai.
✓ Sahi reasoning. Isse originally const defined object modify karne ki permission nahi milti.
- Haan, har alias automatically read-only ho jaata hai.
Ek access path qualify karne se saare pointer objects aur types rewrite nahi hote.
- Pointed-to object pointer mein copy hota hai.
Pointer value object ko refer karti hai; object ki copy contain nahi karti.
C17
Earlier edition ka quick reference
Existing section links aur saved passages ke liye retained. Exact corrections source review mein recorded hain.
Section 7 mein diye gaye brief definitions ko build karte hue, yeh section dekhta hai ki qualifiers aur storage classes actually ek program ke behavior ko kaise shape karte hain.
const, Depth Mein
Sirf const yeh nahi batata ki actually kya constant hai — iski * ke relative position batati hai:
int value = 10;
const int *read_only = &value; /* read_only ke through value change nahi */
int *const fixed = &value; /* fixed reassign nahi; *fixed change ho sakta hai */
const int *const both_fixed = &value; /* reassign aur iske through write, dono nahi */
volatile, Depth Mein
volatile implementation se specified observable accesses preserve karwata hai; access ka exact meaning implementation-defined hai. Typical uses platform rules ke under memory-mapped device registers aur restricted signal-handler idiom ke liye volatile sig_atomic_t flag hain. Yeh read-modify-write ko indivisible nahi banata aur threads ke beech happens-before relationship establish nahi karta. Shared volatile counter mein phir bhi data race ho sakti hai; jahan required ho _Atomic ya mutex use karein.
restrict (C99)
restrict aliasing/access contract hai; iska matlab yeh nahi ki koi doosra pointer value exist hi nahi kar sakta. Associated block execution mein, agar restricted pointer se access hua object modify bhi hota hai, toh us object ke accesses ko restricted-pointer rules follow karne chahiye, normally us pointer ya usse derived values ke through. Sirf read kiye jaane wale objects ki aliasing allowed hai. Contract todna undefined behavior hai; carefully designed array-processing interfaces mein yeh optimization ke liye useful hai.
Storage Duration, Scope, aur Linkage
Teen concepts alag rakhein: object ki storage-duration category uski lifetime ke rules determine karti hai; identifier ka scope hota hai aur linkage ho sakti hai. Function ya typedef name automatic/allocated storage duration wala object nahi hai. Main categories yeh hain:
- Storage duration — automatic (ordinary non-VLA local objects, jinki lifetime block execution follow karti hai; VLA declaration se lekar execution us declaration ke scope se bahar jaane tak jeeta hai), static (jo poore program ke liye exist karte hain, jaise globals ya
staticlocals), allocated (allocation functions se mili storage, jofreese deallocate hone ya successfulreallocse replace hone tak allocated rehti hai), aur thread (C11 ka_Thread_local, jo har thread ko apna independent copy deta hai). - Scope — block scope (sirf apne enclosing
{ }ke andar visible), file scope (declaration ke point se translation unit ke end tak visible), function prototype scope (prototype ke andar parameter names), aur function scope (gototargets ke roop mein use hone wale labels). - Linkage — external (translation units ke across same identifier ki declarations same object ya function ko refer karti hain), internal (ek translation unit ke andar same identifier ki declarations same object ya function ko refer karti hain, commonly file-scope
staticse establish hoti hai), aur none (har declaration distinct entity introduce karti hai, jaise ordinary locals aur parameters). Linkage declarations ko jodti hai; yeh khud kisi name ko visible nahi banati.
Agla idea padhne ke liye tayyar?
Mark this chapter as read whenever you feel ready.