Macros in C

 In C, a macro is a fragment of code defined by the #define directive, which acts as a text substitution tool during the preprocessing stage before compilation. Macros help make code more readable, reusable, and sometimes more efficient by reducing repetitive code.

Types of Macros in C

There are two main types of macros:

  1. Object-like Macros: These are similar to constants or simple code substitutions.
  2. Function-like Macros: These resemble functions but are simply text replacements without the overhead of a function call.

1. Object-like Macros

Object-like macros are used to define constants or static pieces of code. They do not take any arguments.

#define NAME value_or_code

#include <stdio.h>

#define PI 3.14159  // Defines a constant for PI

int main() {
    float radius = 5.0;
    float area = PI * radius * radius;
    
    printf("Area of circle: %.2f\n", area);
    return 0;
}

Explanation:

  • #define PI 3.14159 defines PI as a constant.
  • Everywhere PI appears in the code, it will be replaced by 3.14159 before the code is compiled.

2. Function-like Macros

Function-like macros work similarly to functions but without the overhead of actual function calls. They are defined with parameters, but they perform only text substitution.

Syntax:

#define MACRO_NAME(parameter1, parameter2, ...) expression_using_parameters

Example: Defining a Function-like Macro for Calculations
#include <stdio.h>

#define SQUARE(x) ((x) * (x))  // Squares a number

int main() {
    int num = 4;
    int result = SQUARE(num);
    
    printf("Square of %d is %d\n", num, result);
    return 0;
}

Explanation:

  • #define SQUARE(x) ((x) * (x)) defines a macro called SQUARE that calculates the square of x.
  • When we write SQUARE(num), it gets replaced with ((num) * (num)) during preprocessing, effectively calculating the square of num.

Note on Parentheses:

To avoid unexpected results in macros, use parentheses around parameters and the entire expression. For example, without parentheses, SQUARE(2 + 3) would expand to 2 + 3 * 2 + 3, giving 11 instead of 25.

 Defining a Maximum Macro

#include <stdio.h>

#define MAX(a, b) ((a) > (b) ? (a) : (b))  // Returns the maximum of two numbers

int main() {
    int x = 10, y = 15;
    
    printf("The maximum of %d and %d is %d\n", x, y, MAX(x, y));
    return 0;
}

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays