Constants and Literals in C (const and #define) Explained

Learn how to use constants and literals in C programming. Discover the difference between the const keyword and #define macros for writing secure, bug

Introduction

In Chapter 6, we learned that a variable is a storage box in memory whose contents can change (vary) while the program runs. But what happens when you have a value that should never change?

Imagine you are writing software for a bank to calculate compound interest. The number of months in a year is exactly 12. If another programmer accidentally writes code that changes the number of months to 13, the entire financial system will produce catastrophic errors. To prevent these disasters, software engineers use Constants.

In this chapter, we will learn how to lock our variables so they cannot be tampered with. We will explore the differences between "Literals," the const keyword, and the powerful #define macro.


Illustration showing a locked memory box representing the const keyword and a macro definition representing #define with a blue tech theme.



What are Literals in C?

Before we define constants, we must understand literals. A Literal is raw data written directly into your code. It is a value that cannot be changed because it is hardcoded.

  • Integer Literal: 100, -45
  • Floating-Point Literal: 3.14, 9.81
  • Character Literal: 'A', '#'
  • String Literal: "NeoGyan"

When you write int age = 25;, the number 25 is the literal. The age is the variable holding the literal.



What is a Constant?

A Constant is an identifier (a named storage location, just like a variable) whose value cannot be altered once it is declared. If any part of your code tries to change a constant, the compiler will instantly throw an error and refuse to run.

In C, there are two primary ways to create constants: using the const keyword and using the #define preprocessor directive.



Method 1: The const Keyword

The const keyword is the modern, safest way to define a constant. You use it exactly like a normal variable, but you add the word const at the beginning. This locks the memory box.

const float PI = 3.14159;

Rules for const:

  • You must initialize a const variable at the exact moment you declare it. You cannot write const int x; on one line and x = 10; on the next line.
  • It respects C data types (you explicitly tell it that it is a float, int, etc.).
  • It obeys scope rules (if defined inside a function, it only exists inside that function).

Method 2: The #define Preprocessor (Macros)

This is the older, traditional way of defining constants in C. Instead of using memory boxes, it uses the Preprocessor (which we learned about in Chapter 2).

#define MAX_LIVES 3

Notice that there is no equals sign (=) and no semicolon (;) at the end! Also, we do not specify a data type (like int).

When you use #define, you are creating a Macro. Before the compiler even runs, the preprocessor scans your entire code, finds every instance of the word MAX_LIVES, and literally replaces it with the text 3.



Code Examples

#include <stdio.h>

// Defining a constant using a macro
#define SPEED_OF_LIGHT 299792458 

int main() {
    // Defining a constant using the const keyword
    const float GRAVITY = 9.81;
    
    printf("Physics Engine Initialized.\n");
    printf("Speed of Light: %d m/s\n", SPEED_OF_LIGHT);
    printf("Earth Gravity: %.2f m/s^2\n", GRAVITY);
    
    // The code below will cause an error if uncommented!
    // GRAVITY = 10.0; 
    
    return 0;
}

Code Output

Physics Engine Initialized.
Speed of Light: 299792458 m/s
Earth Gravity: 9.81 m/s^2

Code Explanation

In this code, we demonstrate both methods. SPEED_OF_LIGHT is defined globally using a macro. Before compilation, the preprocessor swaps the word SPEED_OF_LIGHT with the literal number. GRAVITY is defined locally inside main() using the const keyword, meaning it behaves like a locked variable of type float. If we tried to change GRAVITY to 10.0 later in the code, the compiler would block us to prevent a physics glitch in our software.




Common Mistakes for Beginners

  • Adding Semicolons to Macros: Writing #define PI 3.14; is a massive mistake. The preprocessor will replace PI with 3.14;. If you write float area = PI * radius;, it turns into float area = 3.14; * radius;, which causes a syntax error.
  • Forgetting to Initialize const: Writing const int max_speed; and then trying to set it later will fail. The box locks the moment it is created.


Best Practices

  • Use ALL_CAPS for Constants: It is an industry standard to name variables in lowercase (e.g., player_score) and constants in ALL_CAPS (e.g., MAX_SCORE). This helps other engineers instantly recognize that the value cannot be changed.
  • Prefer const over #define: Modern software engineering prefers the const keyword because the compiler can check its data type and catch errors early, whereas #define is just a blind text replacement.

Interview Questions

Q: What is the main difference between const and #define?
Answer: const defines a typed variable stored in memory whose value cannot be changed. #define is a preprocessor directive that performs blind text substitution before compilation, consuming no actual variable memory.

Q: What happens if you try to modify a const variable using a pointer?
Answer: Modifying a const variable via a pointer leads to undefined behavior in C. While some compilers might let you bypass the lock, it is highly dangerous and considered terrible practice.



MCQs

Q1. Which of the following is the correct syntax for a macro?
A) #define PI = 3.14;
B) #define PI 3.14 (Correct)
C) const define PI 3.14;
D) #define float PI 3.14

Q2. Why is it recommended to use uppercase letters for constants?
A) The compiler requires it.
B) It executes faster.
C) It makes them easily distinguishable from normal variables for humans. (Correct)
D) It saves RAM.



Practice Questions

  1. Create a macro for the number of days in a week (7).
  2. Create a const variable for the freezing point of water (0 degrees). Print both values clearly.

Mini Assignment

Write a "Tax Calculator" program. Define a constant for the sales tax rate (e.g., 0.15 for 15%) using the const keyword. Create a variable for a purchase amount (e.g., $50.00). Multiply the purchase amount by the constant tax rate to find the total tax, and print the formatted result.



Conclusion

You now know how to secure your data! Using constants ensures that the critical rules of your software (like physics laws, tax rates, or maximum limits) cannot be accidentally altered by bugs or other developers. This is a massive step toward writing professional-grade code.

So far, we have been hardcoding all our data into our programs. But what if we want the user to type in their own data? In Chapter 10: Input and Output in C, we will finally learn how to make our programs interactive by reading keyboard input using scanf. Get ready to build your first interactive app!



📚 Recommended Reading for Aspiring Developers

Understanding secure data is just the beginning. Discover how data flows through larger, interconnected systems with these premium NeoGyan guides:


About the author

Jayanta Mondal
Jayanta Mondal is a BCA student, web developer, and the founder of NeoGyan. He is passionate about simplifying complex tech concepts for beginners.

Post a Comment