MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

#define to Implement Constants

The #define directive in the C preprocessor is used to create symbolic constants, which are constant values that you can use throughout your code. These constants make the code more readable, easier to maintain, and less error-prone. Here's how it works:

Syntax

#define NAME value

here, NAME: The name of the constant. By convention, constant names are written in uppercase letters, value: The value to be assigned to the constant. This can be a number, a string, or any valid C expression.


Example

#define PI 3.14159 #define MAX_SIZE 100 #define GREETING "Hello, World!"

In this example:

PI is defined as 3.14159, MAX_SIZE is defined as 100, GREETING is defined as "Hello, World!".


Once defined, you can use these constants in your code just like any other variable:

float area = PI * radius * radius; int array[MAX_SIZE]; printf("%s\n", GREETING);

By using #define to implement constants, you can make your code more robust, readable, and easier to maintain.


Report an issue

Reporting: #define to Implement Constants (topic)

Related Posts