C Constants


In C programming, constants are values that do not change during the execution of a program. Unlike variables, which can store data that changes over time, constants provide a way to represent fixed values. Using constants makes programs more readable, maintainable, and less error-prone, because you can refer to a single name instead of repeating the same value multiple times.

This chapter explains different types of constants in C, how to declare them, and their practical applications.

What is a Constant?

A constant is a fixed value that cannot be altered by the program after it is defined. Constants are useful for representing values that should remain unchanged, such as mathematical constants (like π), configuration values, or limits in a program.

Example:

#define PI 3.14159

Here, PI is a constant. Anywhere you use PI in the program, it will be replaced by 3.14159. Trying to change its value later in the program is not allowed.

Types of Constants in C

C provides several ways to define constants:

  1. Literal Constants

  2. const Keyword

  3. #define Preprocessor Macro

  4. Enumerated Constants (enum)

1. Literal Constants

Literal constants are fixed values written directly in the program. They can be of different types:

  • Integer constant: Whole numbers without a decimal point.

    int age = 20; // 20 is an integer constant
    
  • Floating-point constant: Numbers with decimal points.

    float pi = 3.14; // 3.14 is a floating-point constant
    
  • Character constant: A single character enclosed in single quotes.

    char grade = 'A'; // 'A' is a character constant
    
  • String constant: A sequence of characters enclosed in double quotes.

    char name[] = "Lina"; // "Lina" is a string constant
    

2. const Keyword

The const keyword allows you to declare a read-only variable. Once initialized, its value cannot be modified.

Example:

#include <stdio.h>

int main() {
    const int DAYS_IN_WEEK = 7;
    printf("Days in a week: %d\n", DAYS_IN_WEEK);
    // DAYS_IN_WEEK = 8; // This will cause an error
    return 0;
}

Benefits of using const:

  • Improves code readability by giving a meaningful name to a constant value.

  • Prevents accidental modification of critical values.

3. #define Preprocessor Macro

The #define directive allows you to define symbolic constants. It is handled by the preprocessor before the program is compiled.

Syntax:

#define CONSTANT_NAME value

Example:

#include <stdio.h>

#define PI 3.14159

int main() {
    printf("Value of Pi: %.5f\n", PI);
    return 0;
}

Key points:

  • #define constants do not consume memory.

  • They can be used anywhere in the program where the value is needed.

  • They are replaced literally by the preprocessor before compilation.

4. Enumerated Constants (enum)

Enumeration allows you to define a set of named integer constants. It makes code more readable and reduces errors.

Example:

#include <stdio.h>

enum Days {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

int main() {
    enum Days today = Wednesday;
    printf("Today is day number: %d\n", today); // Output: 2
    return 0;
}
  • By default, enumeration constants start from 0 and increase by 1.

  • You can also assign specific values:

    enum Months {Jan = 1, Feb, Mar, Apr};
    

Advantages of Using Constants

  1. Readability: Using constants with descriptive names makes the code easier to understand.

  2. Maintainability: If a value changes, you only need to update it in one place.

  3. Error Prevention: Prevents accidental changes to critical values.

  4. Memory Efficiency: Constants defined with #define or enum do not occupy memory like variables.

Examples of Using Constants

Example 1: Using const

#include <stdio.h>

int main() {
    const float TAX_RATE = 0.18; // 18% tax rate
    float price = 100;
    float tax = price * TAX_RATE;

    printf("Tax: %.2f\n", tax);
    return 0;
}

Output:

Tax: 18.00

Example 2: Using #define

#include <stdio.h>

#define MAX_USERS 50

int main() {
    printf("Maximum users allowed: %d\n", MAX_USERS);
    return 0;
}

Output:

Maximum users allowed: 50

Example 3: Using enum

#include <stdio.h>

enum Colors {Red = 1, Green, Blue};

int main() {
    enum Colors favorite = Blue;
    printf("Favorite color number: %d\n", favorite);
    return 0;
}

Output:

Favorite color number: 3

Best Practices for Constants

  1. Use meaningful names:
    Instead of using numbers directly, use descriptive names like MAX_SCORE, PI, or DAYS_IN_WEEK.

  2. Prefer const over literal values:
    It provides type checking and is safer than #define.

  3. Group related constants:
    Use enum or #define for sets of related constants to improve readability.

  4. Avoid magic numbers:
    Replacing hardcoded numbers with constants makes your code easier to understand and maintain.

Summary of the Tutorial

Constants are fixed values that do not change during program execution. C provides multiple ways to define constants: literal constants, const keyword, #define macros, and enumerations. Using constants improves code readability, maintainability, and reduces errors. Proper use of constants also ensures that critical values remain unchanged, making your programs more robust and professional.


Practice Questions

  1. What is a constant in C, and how does it differ from a variable?

  2. Write a const declaration for a floating-point variable named TAX_RATE with a value of 0.18.

  3. Explain the difference between #define and const for creating constants.

  4. What is an enumerated constant (enum) in C? Give an example.

  5. Identify the error in the following code:

    const int MAX_USERS;
    MAX_USERS = 50;
    
  6. Write a program using #define to create a constant for the maximum number of students, set to 30, and print it.

  7. Why is it considered good practice to avoid “magic numbers” in your code?

  8. Explain the advantage of using meaningful names for constants instead of using literal values directly.

  9. Create an enumeration for the four seasons and assign Summer the value 1.

  10. How does using constants help prevent errors in a program?


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top