Ways to define Constant in C

By | February 14, 2023

Prerequisite – Constants in C
In C programming language, there are several ways to define a constant, depending on the type of constant and where it is used in the program. Here are the most common ways to define a constant in C:

  1. Using the “const” keyword –
    The “const” keyword can be used to define constants in C. For example, to define an integer constant named “MAX” with the value 100, the following syntax can be used:

    const int MAX = 100;
    
  2. Using the “#define” preprocessor directive –
    The “#define” preprocessor directive can also be used to define constants in C. For example, to define an integer constant named “MAX” with the value 100, the following syntax can be used:

    #define MAX 100
    
  3. Using the “enum” keyword –
    The “enum” keyword can be used to define a set of named constants in C. For example, to define an enum named “Days” with the values “Monday”, “Tuesday”, “Wednesday”, etc., the following syntax can be used:

    enum Days {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
    
  4. Using “const” with pointers –
    Constants can also be defined using pointers in C. For example, to define a constant string named “GREETING” with the value “Hello, world!”, the following syntax can be used:

    const char* GREETING = "Hello, world!";
    

Note that using the “const” keyword is considered a safer and more modern way of defining constants in C, as it provides type checking and other benefits. The use of the “#define” preprocessor directive is less recommended, as it can lead to potential errors and is less safe.

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.