Constants in C const vs define

Learn how to use constants in C programming on Debian 12. This tutorial covers both const keyword and #define preprocessor with practical examples.

Understanding Constants in C Programming

Constants in C are fixed values that cannot be altered during program execution. Using constants makes your code more readable and maintainable. In C, there are two main ways to define constants: using the const keyword and the #define preprocessor directive.

The const Keyword

The const keyword creates a read-only variable. Once initialized, its value cannot be changed. The syntax is:

const type name = value;

For example:

const float PI = 3.14159;
const int MAX_USERS = 100;

Key characteristics:

  • Has data type and scope rules like normal variables
  • Allocated storage in memory
  • Can be used for array sizes in C99 and later

The #define Preprocessor

#define creates macro constants that are replaced by the preprocessor before compilation:

#define NAME value

For example:

#define PI 3.14159
#define MAX_USERS 100

Key characteristics:

  • No memory allocation - simple text replacement
  • No type checking
  • Global scope from point of definition

Example Program

Let's write a program demonstrating both constant types:

#include 

#define TAX_RATE 0.07

int main() 
    const float DISCOUNT = 0.15;
    float price = 100.0;
    
    printf(\\"Original price: $%.2f\
\\", price);
    printf(\\"After %.0f%% discount: $%.2f\
\\", 
           DISCOUNT*100, price*(1-DISCOUNT));
    printf(\\"Plus %.0f%% tax: $%.2f\
\\",
           TAX_RATE*100, price*(1-DISCOUNT)*(1+TAX_RATE));
    
    return 0;

When to Use Each

Use const when:

  • You need type safety
  • You want scope control
  • Working with pointers to constants

Use #define when:

  • You need compile-time constants for array sizes
  • Creating header file guards
  • Defining values used in multiple source files

Best Practices

  • Use uppercase names for constants (CONSTANT_NAME)
  • Prefer const for type safety in most cases
  • Place #define directives at the top of files
  • Document the purpose of each constant

Conclusion

Both const and #define have important roles in C programming. Understanding their differences helps you write better, more maintainable code. Practice using both in different scenarios to become comfortable with each approach.

Subscribe to Our YouTube for More

Download as PDF

https://blog.arashtad.com/updates/constants-in-c-const-vs-define/?feed_id=11877&_unique_id=687a795a3e769

Comments

Popular posts from this blog

Why Smart Contracts Are Revolutionary? (Smart Contracts Use Cases)

A Quick Guide to Tron Network Interaction using Python.

WordPress: The best CMS platform to create website