Topic 13 of 100 Data Types and Variables Interactive Tutorial

Constants in C: Fixed Values, Declaration Methods, and Examples

11 mins read Last updated: 22 Aug 2026 18,200 views
C Compiler 0.00%

What is Constants in C? Core Concept & Direct Summary

Core Objective & Problem Statement

What are the different ways to define constants in C using `const`, `#define`, and `enum`?

Direct Answer Summary

Some values should never change. The number of days in a week. The value of π. The maximum score on a test. The speed of light.

Now imagine writing a program where someone — future-you, a teammate, a tired intern — accidentally typesPI = 4.0somewhere in the middle of 5,000 lines. Your geometry calculations silently go insane, and nobody knows why.

C's answer to this problem is theconstant: a value locked in place, immune to modification. In this guide, you'll learn the two ways to create constants in C (constand#define), the differentkindsof constant values C recognizes, and the practical judgment about which method to use when.

Let's lock some values down.

How Does Constants in C Work? In-Depth Mechanics & Architecture

What Is a Constant in C?

Aconstantis a value that cannot be modified after it's defined. Where a variable is a box you can empty and refill, a constant is a box that's beenwelded shut.

main.c
Run Online
const int DAYS_IN_WEEK = 7;
DAYS_IN_WEEK = 8;
// ❌ COMPILER ERROR — constants refuse to change

That compiler error is the entire point. The mistake gets caughtbeforethe program ever runs — not at 2 AM in production when a customer calls.

Constants deliver three benefits:

  1. Safety— accidental modification becomes impossible
  2. Readability—DAYS_IN_WEEKexplains itself; a bare7doesn't
  3. Maintainability— change the value inone place, and it updates everywhere it's used

That last benefit is bigger than it sounds. If a tax rate is hard-coded as0.18in 47 places across your program, changing the rate means 47 edits and 47 chances to miss one. As a constant? One edit. Done.

Method 1: The const Keyword (The Modern Way)

Theconstqualifier turns any variable declaration into a locked constant:

main.c
Run Online
#include <stdio.h>
int main() {
    const float PI = 3.14159f;
    const int MAX_ATTEMPTS = 3;
    const char GRADE_A = 'A';
    printf("PI: %.5f\n", PI);
    printf("Max attempts: %d\n", MAX_ATTEMPTS);
    return 0;
}

Key facts aboutconst:

  • It's type-checked— the compiler knowsPIis afloat, so format specifiers, conversions, and warnings all work normally
  • It must be initialized at declaration—const int x;followed byx = 5;is illegal; once declared, the value is frozen
  • It has scope— aconstdeclared inside a function is local to that function, just like a variable

Try modifying one and see the compiler's disapproval firsthand:

main.c
Run Online
const int MAX = 100;
MAX = 200;
// error: assignment of read-only variable 'MAX'

The compiler literally calls itread-only— a perfect description.

Method 2: The #define Directive (The Classic Way)

Beforeconstexisted, C used thepreprocessorfor constants — and this method is still everywhere:

main.c
Run Online
#include <stdio.h>
#define PI 3.14159
#define MAX_STUDENTS 100
#define APP_NAME "GradeCalc"
int main() {
    printf("PI: %.5f\n", PI);
    printf("Capacity: %d students\n", MAX_STUDENTS);
    printf("Welcome to %s\n", APP_NAME);
    return 0;
}

Here's the crucial difference inhowit works:#defineperforms atext replacementbefore compilation. The preprocessor literally finds everyPIin your code and swaps in3.14159— the compiler never sees the name at all. It's a search-and-replace operation, not a variable.

Notice the style details:

  • No semicolonat the end (it's a preprocessor directive, not a statement)
  • No=sign— just the name and the replacement text
  • ALL_CAPS naming— the universal convention that screams "I'm a constant!"

const vs #define: Which Should You Use?

This is the question every C learner asks, so here's the honest comparison:

Aspectconst#define
Type safety✅ Has a real type — compiler checks it❌ Just text — no type checking
Scope✅ Respects block/function scope❌ Global from definition onward
Debugging✅ Name appears in debuggers❌ Name vanishes before compilation
MemoryOccupies memory like a variableNo memory — pure text swap
Array sizes❌ Not allowed in C89 (allowed in C99+ VLAs)✅ Works everywhere
When it happensCompile timePre-compile time

The modern consensus:preferconstfor values — it's safer, scoped, and debuggable. Use#definefor thingsconstcan't do (array sizes in older standards, conditional compilation, macros with logic).

main.c
Run Online
const int MAX_SCORE = 100;
// ✅ modern, safe, preferred#define MAX_SCORE 100          // ✅ classic, still everywhereconst int max;
// ❌ error — const must be initialized

[IMAGE 2 — Infographic: const vs #define Showdown]Design:VS-battle style card — left sideconst(green checkmarks: typed, scoped, debuggable), right side#define(blue checkmarks: works for array sizes, macros). Verdict banner: "Prefer const for values."Alt text:Difference between const keyword and define directive in C comparison table

The Literal Constants: Fixed Values You Write Directly

Beyond named constants, C recognizesliteral constants— fixed values typed straight into code. You've been using them all along:

Integer Constants

main.c
Run Online
int a = 42;
// decimalint b = 052;
// octal (leading 0) — equals 42!int c = 0x2A;
// hexadecimal (leading 0x) — also 42!int d = 0b101010;
// binary (C23) — yes, still 42!long e = 42L;
// long — note the L suffixunsigned f = 42U;
// unsigned — the U suffix

Yes,42,052,0x2A, and0b101010are thesame numberwearing different outfits. The leading0for octal is a famous trap — writeint pincode = 042;and you won't get 42.

Floating-Point Constants

main.c
Run Online
float x = 3.14f;
// float — the f suffix matters!
double y = 3.14;
// double (the default for decimals)
double z = 1.5e3;
// scientific notation: 1.5 × 10³ = 1500.0
double tiny = 2.5e-4;
// 0.00025

Beginner trap:without thef,3.14is adouble, and storing it in afloatsilently demotes the precision. Old compilers warn; new habits don't need warnings.

Character Constants

main.c
Run Online
char letter = 'A';
// single quotes — single character
char digit = '7';
// this is the CHARACTER 7 (ASCII 55), not the number 7!
char newline = '\n';
// escape sequences are single characters too

Remember the golden rule from our tokens discussion:'A'(character) and"A"(string) aredifferent thingsin C. Single quotes = one character. Double quotes = a string.

String Constants

main.c
Run Online
char greeting[] = "Hello, C!";
// a string literal

String literals get stored in read-only memory — which means this classic mistake crashes programs:

main.c
Run Online
char *name = "Ravi";
name[0] = 'K';
// 💥 undefined behavior — string literals are read-only!

A Complete Working Example

All constant styles cooperating in one program:

main.c
Run Online
#include <stdio.h>
#define TAX_RATE 0.18 // #define constant
#define CURRENCY "INR" // string constant via define
int main() {
    const int QUANTITY = 3;
    // const constant
    const float PRICE = 499.99f;
    // const float
    float subtotal = PRICE * QUANTITY;
    float tax = subtotal * TAX_RATE;
    float total = subtotal + tax;
    printf("Subtotal: %.2f %s\n", subtotal, CURRENCY);
    printf("Tax (18%%): %.2f %s\n", tax, CURRENCY);
    printf("Total:    %.2f %s\n", total, CURRENCY);
    return 0;
}

Output:

main.c
Run Online
Subtotal: 1499.97 INR
Tax(18%): 269.99 INR
Total: 1769.96 INR

Notice how the business logic reads almost like English —subtotal * TAX_RATE— because the constants carry meaning. And if the tax rate changes to 20%? One line edited, entire program updated.

Best Practices at a Glance

  1. Name constants in ALL_CAPS—MAX_SIZE,PI,TAX_RATE
  2. Preferconstfor typed values; use#definefor array sizes and macros
  3. Never hard-code "magic numbers"— if a value has meaning, name it
  4. Define once, use everywhere— that's the entire maintenance superpower
  5. Don't modify string literals— they're read-only, and C won't warn you politely

Runnable C Code Example & Practical Implementation

main.c
Run Online
#include <stdio.h>
#define APP_VERSION "2.5.0"
const int MAX_USERS = 500;
enum Status {
    SUCCESS = 0,
    WARNING = 1,
    ERROR = 2
};
int main() {
    printf("Version: %s\
", APP_VERSION);
    printf("Max Users: %d\
", MAX_USERS);
    printf("Status Code Error: %d\
", ERROR);
    return 0;
}

Key Takeaways, Best Practices & Memory Safety Rules

Best Practice & Key Takeaways
Prefer const variables and enum over #define for typed numeric constants to benefit from compiler type safety.

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked C programming interview questions
Q

Q: What is the main advantage of `const` over `#define`?

A: `const` constants are strictly type-checked by the compiler, obey block scoping rules, and appear in debuggers with symbol information, whereas `#define` is untyped textual substitution.
Q

Q: Can you modify a `const` variable via a pointer in C?

A: Casting away `const` and modifying it (`*(int*)&const_var = 10;`) invokes undefined behavior if the variable is stored in read-only memory.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations