Table of Contents
This is a simple demonstration of a Macro in C language. This is program is written using Turbo C++ Compiler installed on a Windows XP 64-bit system. You can compile and run this program using an standard C compiler.
This program is intended for intermediate level learners who know how to write a complex C program.
Problem Definition
The program to compute the area of a square use a C macro called ” area (r) r * r “ where r is a parameter which can be replaced with any variable.
Macro code gets replaced directly where they appear within the program and then executed as regular C tokens.
The are declared and defined at the beginning of a C program using #define keyword.
The area(r) receives a variable value called “Length_of_Side” for a square and computes the area of a square.
Program Code
/* Program to find area of square using Macro in c */
#include <stdio.h>
#include <stdlib.h>
#define area(r) (r * r)
main()
{
int length_of_side;
int area_of_square;
/* Read the Length of Side of a Square */
printf("Enter the length of side in 'cm' of a Square:");
scanf("%d",&length_of_side);
/* Calling Macro area(r) where r is length_of_side */
area_of_square = area(length_of_side);
printf("Area of Square = %d",area_of_square);
printf("cm(square)");
getch();
return 0;
}The program receives the “length of side” in following code.
scanf("%d", &length_of_side);The length of side is an integer data type.
The area of square is computed using following macro.
area of square = area(lenght_of_side);It is quickly replaced with r * r and area of square is computed.
Output
Enter the length of side in 'cm' of a square:12
Area of Square = 144cm(square)