0
0
Cprogramming~5 mins

Constants and literals

Choose your learning style9 modes available
Introduction

Constants and literals let you use fixed values in your program that do not change. This helps keep your code clear and safe.

When you want to use a value that should never change, like the number of days in a week.
When you want to make your code easier to read by giving a name to a fixed value.
When you want to avoid mistakes by preventing accidental changes to important values.
When you need to use fixed text or numbers directly in your program.
When you want to improve program performance by using fixed values.
Syntax
C
#define NAME value
const type NAME = value;

#define creates a constant by replacing text before compiling.

const creates a typed constant variable that cannot be changed.

Examples
This defines a constant named DAYS_IN_WEEK with the value 7 using #define.
C
#define DAYS_IN_WEEK 7
This defines a constant integer variable named daysInWeek with the value 7 using const.
C
const int daysInWeek = 7;
This defines a constant character named letter with the value 'A'.
C
const char letter = 'A';
This defines a constant floating-point number named pi with the value 3.14.
C
const float pi = 3.14f;
Sample Program

This program shows how to use #define and const to create constants. It prints the maximum and passing scores.

C
#include <stdio.h>

#define MAX_SCORE 100

int main() {
    const int passingScore = 60;
    printf("Maximum score is %d\n", MAX_SCORE);
    printf("Passing score is %d\n", passingScore);
    return 0;
}
OutputSuccess
Important Notes

Constants created with #define have no type and are replaced before the program runs.

Constants created with const have a type and are checked by the compiler.

Use const when you want type safety and #define for simple text replacement.

Summary

Constants hold fixed values that do not change during program execution.

#define and const are two ways to create constants in C.

Using constants makes your code easier to read and less error-prone.