C Constants

A constant is a value which cannot be changed after it is set. We use constants for fixed values like pi or the number of days in a week.

Using the const keyword

#include <stdio.h>

int main(void) {
    const float PI = 3.14159f;
    float radius = 5;

    printf("Area = %.2f\n", PI * radius * radius);
    // PI = 3.14;   <- this line would give a compile error
    return 0;
}

Output:

Output of the above program is

Area = 78.54

Using #define

#define creates a symbolic constant. The preprocessor replaces its name with the value before compiling. There is no semicolon at the end.

#include <stdio.h>
#define MAX_STUDENTS 50
#define COLLEGE "ABC College"

int main(void) {
    printf("%s has %d students\n", COLLEGE, MAX_STUDENTS);
    return 0;
}

Output:

Output of the above program is

ABC College has 50 students

const vs #define

Propertyconst#define
TypeHas a data typeNo type, simple text replace
ScopeFollows normal scope rulesFrom the line it is written
MemoryTakes memory like a variableNo memory used
DebuggingVisible in the debuggerNot visible

Literal constants

KindExample
Integer10, -5, 0x1F
Float3.14, 2.5e3
Character'A', '\n'
String"Hello"
Note: By habit, constant names are written in capital letters, like MAX_SIZE.

Next: C printf and scanf.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to swap the values of two variables using a third variable
Write a C program to print words using spacing and new line characters
Write a C program to get the salary from the user and print it
Write a C program to find the size of int, float, long, double and char
Write a C program to get the marks of 5 subjects and find the total and average
Write a C program to calculate the perimeter of a rectangle
Write a C program to convert minutes into hours and minutes
Interview Questions & Answers
What is the difference between a variable and a constant in C?
What are the data types in C?
What is the difference between = and == in C?
What is the difference between ++i and i++ in C?
What is the use of the sizeof operator in C?
How to swap two numbers in C?