YOUR C LEARNING COMPANION

Kahan se padhein?

Learning path
Language ki detailsChapter 18 of 73

Constants, constant expressions aur compile-time checks

Literals, enumeration constants, macros, const objects aur C23 constexpr ko required contract se choose karein.

7 min readFoundationsC17 + C23 notes
Offline reading
Is chapter mein10 sections

Ek run mein value na badle, toh bhi C use har compile-time jagah accept nahi karti. Yeh chapter literals, read-only objects aur constant expressions ko alag karta hai, taaki constant shabd ke peeche ke different rules clear hon.

1. Fixed-looking value likhne ke chaar forms

FormC17 mein kya milta haiKab useful hai
4Integer constant token; spelling aur range se type decide hota haiValue locally clear ho.
enum { COUNT = 4 };Named enumeration constant; yahan type int haiConstant-expression contexts ke liye small named integer chahiye.
#define COUNT 4Preprocessing token replacement, typed object declaration nahiPreprocessing decision ko spelling chahiye ya established interface macro use karta ho.
const int count = 4;Typed read-only object; ordinary reads integer constant expressions nahiProgram ko read-only access wala object chahiye.

Constant expression language-defined category ka member hai. Compiler expression ko ek value mein optimize kar sakta hai ya nahi, usse category decide nahi hoti. Macro constant expression, function call ya kuch aur expand kar sakta hai; result expansion par depend karta hai.

2. Integer constant expressions ke specific contexts hain

C17 · illustrative fragment
#define COLUMN_COUNT 4
enum { ROW_COUNT = 3 };
const int selected_row = 1;
int values[ROW_COUNT][COLUMN_COUNT] = { { 0 } };
_Static_assert(ROW_COUNT * COLUMN_COUNT == 12, "grid contract");
values[selected_row][2] = 7;
#undef COLUMN_COUNT

ROW_COUNT aur macro-expanded COLUMN_COUNT constant array bounds dete hain. selected_row ordinary indexing mein used const object hai; usko constant expression hona zaroori nahi. Static assertion translation time par 12-element design check karta hai. Array aur indexing chhota preview hain; understanding arrays boundaries develop karta hai.

C17 integer constant expressions ka integer type aur restricted operands hote hain: integer/enumeration/character constants, suitable sizeof results, _Alignof expressions, aur specified limited casts/unevaluated-operand exceptions. Evaluated constant expressions mein function calls, assignments, increments aur comma operators generally allowed nahi. Rule ko “sirf literal numbers” ya “kuch bhi pure” mat bana dein.

Case labels, enumeration values, static assertions aur non-VLA array bounds ke constant-expression requirements ke saath further constraints bhi hote hain. Arbitrary runtime int unka replacement nahi.

Intentional diagnostic: const object C17 integer constant expression nahi
C17 · intentional build rejection
const int count = 4;
_Static_assert(count == 4, "not an integer constant expression in C17");

Initializer 4 hone se count ke read ki classification nahi badalti. C17 mein yahan enumeration constant use karein, ya C23 rules ke under suitable constexpr object.

3. Storage duration har initializer ko valid nahi banati

C17 static/thread-duration object initializers ko initialization rules ke hisaab se constant expressions ya string literals use karne hote hain. Allowed forms sirf integer constant expressions nahi: address constant se static-duration object ka pointer initialize kar sakte hain.

Complete C17 program
#include <assert.h>

static int object;
static int *saved_address = &object;

int main(void)
{
    assert(saved_address == &object && *saved_address == 0);
    return 0;
}

saved_address existing static object ke address se initialize hota hai. Isse ordinary function call ko C17 static initializer mein permission nahi milti. Usi tarah const declaration later use ko automatically valid file-scope array bound nahi banati.

Intentional diagnostic: file scope par variable length array
C17 · intentional build rejection
const int count = 4;
int values[count];

C17 mein count object hai, isliye bound integer constant expression nahi. Resulting variably modified type file scope par allowed nahi. Block ke andar VLA alag feature hai, jiske optional-support aur positive-bound requirements hain; const add karna usko fixed-size array nahi banata.

4. Mentioned expression ko execute hona zaroori nahi

C17 · illustrative fragment
int value = 3;
size_t width = sizeof(value++);

Operand ka type int hai, isliye sizeof value++ evaluate kiye bina size C bytes mein deta hai. value 3 hi rehta hai. Result ka type size_t hai. Yeh specific sizeof result integer constant hai; VLA types mein size computation runtime evaluation involve kar sakti hai aur standard ke additional exceptions hain.

C17 _Alignof(type-name) type ki alignment query karta hai. Yeh pointer access try karne wala runtime probe nahi. Constant-expression requirement aur unevaluated operand related language rules hain; arbitrary invalid syntax insert karne ki permission nahi.

5. #if preprocessing information dekhta hai, C objects nahi

#if COLUMN_COUNT == 4 jaisi condition expanded macro tokens use kar sakti hai. Preprocessor ordinary const objects ya enumeration constants look up nahi karta. Macro replacement aur specified processing ke baad C17 #if mein remaining identifiers zero se replace hote hain. Isliye misleading condition wrong branch select kar sakti hai, jabki later C declaration correct dikhti hai.

Translation se pehle source/configuration choose karne ke liye preprocessing use karein. Suitable C type/value contracts ke liye _Static_assert use karein. Sirf execution mein known values ke liye runtime check use karein. Runtime assert NDEBUG se disable ho sakta hai; untrusted input ya required side-effect operation ki sole validation uspar mat rakhein.

6. C23: constexpr named constant object add karta hai

C23 mein constexpr int count = 4; const-qualified object define karta hai, jiska identifier appropriate constant expressions mein participate kar sakta hai. static_assert(count == 4); C23 illustration hai. C23 single-argument static_assert form bhi allow karta hai; C17 _Static_assert ko message argument chahiye.

C23 constexpr object feature hai, C++ wala constexpr functions define karne ka feature nahi. Initializers aur object types ko constraints satisfy karne hote hain, including relevant exact-representability requirements. Arbitrary calls valid constant initializers nahi ban jaati. Static ke bina block constexpr object ki automatic duration ho sakti hai; file-scope constexpr identifier ki internal linkage hoti hai. Read-only access, constant-expression use, linkage aur duration alag rehte hain.

Inline C23 forms source-reviewed version notes hain. Page ke runnable examples C17 use karte hain; project mein naye forms lene se pehle actual compiler aur library support check karein.

7. Thought check: optimizer language rule badal sakta hai?

Compiler const object ka read fold karke 4 banata hai. Kya ab yeh C17 case-label constant hai?

Nahi. Optimization valid program ko implement karne ka tareeka badal sakta hai; expression ko source-language constant-expression requirement satisfy nahi karwa deta. Pehle selected standard se admitted form choose karein, phir unhi rules ke andar optimize karein.

Sources aur aage ki reading

Primary references: WG14 N1570 6.4.4, 6.5.3.4, 6.6, 6.7.9, 6.7.10, and 6.10.1; WG14 N3096 (C23 notes). These are public committee drafts; the examples here use a C17 baseline.

Aage badhne se pehle

  • Literals, enumeration constants, read-only objects aur constant expressions alag categories hain.
  • Context ko sirf unchanged runtime value ke bajaye integer constant expression chahiye ho sakta hai.
  • C23 constexpr objects ke apne rules hain; C++ constexpr functions nahi milte.
In ideas ko alag rakhein
const / Constant expression
C17 mein ordinary const object automatically integer constant expression nahi hai.
Apne words mein samjhaayein

Same numeric value wali do declarations different compile-time contexts mein differently accept kyun ho sakti hain?

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.

C17 mein kya sirf const int n = 3; se n integer constant expression ban jaata hai?
Har choice ki explanation padhein
  1. Haan, const har compile-time constant facility jaisa kaam karta hai.

    Read-only qualification aur integer-constant-expression rules alag concepts hain.

  2. Nahi. Sirf const qualification woh rule satisfy nahi karti.

    ✓ Sahi reasoning. Relevant constant-expression context mein allowed form use karein, jaise suitable enumerator ya integer constant.

  3. Isse n use karne wala har array har context mein invalid hota hai.

    Supported facility aur context mein nonconstant bound VLA bana sakta hai.

C17

Agla idea padhne ke liye tayyar?

Mark this chapter as read whenever you feel ready.

CHAPTER 18 / 73

Is chapter mein

Constants, constant expressions aur compile-time checks

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping