Home C C constants tutorial with code examples

C constants tutorial with code examples

In C programming, constants are fixed values that cannot be changed during the execution of a program.

Constants help make code more readable and maintainable by using descriptive names for fixed values.

C provides several ways to define constants, including using the const keyword, the #define preprocessor directive, and enumerations.

1. Constants Using const Keyword

The const keyword is used to declare a constant variable.

Once a variable is declared with const, its value cannot be modified.

Syntax:

const data_type variable_name = value;

Example: Using const for a Constant Variable

#include <stdio.h>

int main() {
    const int MAX_SIZE = 100; // Declares a constant integer

    printf("The maximum size is: %d\n", MAX_SIZE);

    // MAX_SIZE = 200; // Error: cannot assign a new value to a const variable

    return 0;
}

In this example:

  • MAX_SIZE is a constant integer, so its value cannot be modified.
  • Attempting to reassign MAX_SIZE will result in a compile-time error.

Example: Using const with Different Data Types

#include <stdio.h>

int main() {
    const float PI = 3.14159;       // Floating-point constant
    const char NEWLINE = '\n';      // Character constant

    printf("Value of PI: %.5f", PI);
    printf("%c", NEWLINE);          // Prints a new line using NEWLINE constant

    return 0;
}

In this example:

  • PI is a constant of type float, used for storing the value of π.
  • NEWLINE is a char constant holding the newline character.

2. Constants Using #define Preprocessor Directive

#define is a preprocessor directive used to define a symbolic constant. It replaces all occurrences of the constant name with its value before compilation.

Syntax:

#define CONSTANT_NAME value

Example: Defining a Constant Using #define

#include <stdio.h>

#define LENGTH 10
#define WIDTH 5

int main() {
    int area = LENGTH * WIDTH;
    printf("Area of rectangle: %d\n", area);

    return 0;
}

In this example:

  • LENGTH and WIDTH are defined constants using #define.
  • The area of a rectangle is calculated using these constants.

Example: Using #define for Complex Constants

#include <stdio.h>

#define PI 3.14159
#define AREA_OF_CIRCLE(radius) (PI * (radius) * (radius))

int main() {
    float radius = 4.5;
    float area = AREA_OF_CIRCLE(radius);

    printf("Area of the circle: %.2f\n", area);

    return 0;
}

In this example:

  • AREA_OF_CIRCLE(radius) is a macro that calculates the area of a circle.
  • PI is a defined constant that is used within the macro.

3. Enumeration Constants (enum)

An enum (enumeration) is a user-defined data type that consists of a set of named integer constants. It’s commonly used to define values with a limited set of options.

Syntax:

enum EnumName { CONSTANT1, CONSTANT2, ..., CONSTANTN };

Example: Using enum to Define Days of the Week

#include <stdio.h>

enum Weekday { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };

int main() {
    enum Weekday today = WEDNESDAY;

    printf("The value of today: %d\n", today); // Outputs 3 as enums start from 0 by default

    return 0;
}

In this example:

  • enum Weekday defines days of the week as integer constants starting from 0.
  • today is set to WEDNESDAY, which is represented by 3.

Example: Custom Values for Enumeration Constants

You can assign custom values to enum constants.

#include <stdio.h>

enum SeverityLevel { LOW = 1, MEDIUM = 5, HIGH = 10, CRITICAL = 15 };

int main() {
    enum SeverityLevel alertLevel = CRITICAL;

    printf("Alert level: %d\n", alertLevel);

    return 0;
}

In this example:

  • Each severity level is assigned a specific integer value.
  • alertLevel is set to CRITICAL, represented by the value 15.

4. Differences Between const, #define, and enum

Feature const #define enum
Type Has a specific type Type-less Integer type only
Scope Respects C scope rules Global, no scope rules Can be limited in scope like variables
Memory Allocates memory No memory allocation, replaced at compile-time Allocates memory per enum variable
Debugging Easier to debug Harder to debug, no type checking Provides symbolic names for integer constants
Best Use Constant variable values Literal values, constants that don’t need a type Set of related constants with known integer values

5. Practical Examples

Example: Using const and #define Together

You can combine const and #define to declare different types of constants within the same program.

#include <stdio.h>

#define PI 3.14159
const int MAX_USERS = 100;

int main() {
    int radius = 5;
    float area = PI * radius * radius;

    printf("Area of circle: %.2f\n", area);
    printf("Max users allowed: %d\n", MAX_USERS);

    return 0;
}

In this example:

  • PI is a constant value defined using #define.
  • MAX_USERS is declared with const, allowing it to be treated as a variable with scope and type.

Example: Enumerations and #define Constants Together

#include <stdio.h>

#define TAX_RATE 0.15

enum CustomerType { REGULAR = 1, VIP, STUDENT };

int main() {
    enum CustomerType customer = VIP;
    float basePrice = 100.0;
    float finalPrice = basePrice * (1 + TAX_RATE);

    if (customer == VIP) {
        finalPrice *= 0.9; // 10% discount for VIPs
    }

    printf("Final price for customer type %d: %.2f\n", customer, finalPrice);

    return 0;
}

In this example:

  • TAX_RATE is a constant defined using #define.
  • enum CustomerType defines three types of customers.
  • A discount is applied if the customer is VIP.

Example: Constants in Expressions and Functions

Constants can be used in calculations and passed to functions like regular variables.

#include <stdio.h>

#define GRAVITY 9.8

float calculateWeight(float mass) {
    return mass * GRAVITY;
}

int main() {
    float mass = 75.0;
    printf("Weight on Earth: %.2f\n", calculateWeight(mass));

    return 0;
}

In this example:

  • GRAVITY is used as a constant in the calculateWeight function.
  • It makes the code more readable by using a symbolic name for a known constant value.

Summary

  • const Keyword: Used to define variables with constant values. The compiler enforces immutability, and the constant has a data type.
  • #define Directive: Used to define symbolic constants or macros. It does not allocate memory or enforce type checking.
  • enum Type: Used for defining a set of named integer constants, often used for values that represent a set of known options.

Final Example: Combining All Types of Constants

#include <stdio.h>

#define MAX_SPEED 120  // Max speed limit
const float PI = 3.14159; // Circle constant
enum Direction { NORTH = 1, EAST, SOUTH, WEST }; // Directions

int main() {
    int speed = 100;
    float radius = 10.0;
    enum Direction travelDir = EAST;

    if (speed > MAX_SPEED) {
        printf("Warning: Speed limit exceeded!\n");
    } else {
        printf("Speed is within the limit.\n");
    }

    printf("Circumference of a circle with radius %.2f: %.2f\n", radius, 2 * PI * radius);
    printf("Traveling in direction: %d\n", travelDir);

    return 0;
}

In this final example:

  • MAX_SPEED is defined using #define, making it a literal constant for maximum speed.
  • PI is declared with const, providing a typed constant for mathematical calculations.
  • enum Direction defines constants for directions.

This tutorial covers the basics of defining and using constants in C, showing you how const, #define, and enum can help improve readability, safety, and maintainability in your code.

 

You may also like