top of page
Writer's pictureAishwarya Dutta

What are Macros in C?




What are Macros in C Language?


Macros in C are essentially a piece of code or a value that is associated with an identifier. This identifier, known as the macro name, is defined using the #define preprocessor directive. Macros provide a convenient way to substitute code snippets or values throughout your program, improving both readability and maintainability.


Macros are not pointers to memory locations; instead, they are symbolic representations that the compiler replaces with the actual value or code before the program is compiled.

Let's break down the components of a macro using the following syntax:


#define MACRO_NAME MACRO_VALUE

Here, MACRO_NAME is the name you choose for your macro, and MACRO_VALUE is the corresponding value or code snippet. It's important to note that macros do not end with a semicolon.


Let's illustrate this with an example:


#include <stdio.h>

// Define a macro for the value of pi

#define PI 3.14159

int main() {

   double radius = 5.0;

   double area = PI  radius  radius;

  

   printf("The area of the circle is: %lf\n", area);

  

   return 0;

}


In this example, the macro PI is defined with the value 3.14159. When the code is preprocessed, every occurrence of PI in the code is replaced with its corresponding value, resulting in efficient and readable code.


Preprocessor and Preprocessor Directives in C

Before a C program is compiled, it undergoes preprocessing, a stage where the preprocessor handles various directives indicated by the # symbol. Preprocessor directives provide instructions to the compiler on how to process the code before compilation. For macros, the #define directive is used to define macros, allowing you to specify a macro name and its corresponding value or code snippet. When the code is preprocessed, the macro name is replaced with its value throughout the program.


For More, check the Web development course

8 views0 comments

Recent Posts

See All

コメント


bottom of page