C Program To Find Cube Of Number Using MACRO

What are Macros in C?

It is a preprocessor directive that contains some constant value and before the actual compilation starts,
it replaces the text from the quote that means if you assigned any value to it, it will not be called or like a variable,
it will not be used, but it will replace the text which will be compiled by the compiler.

for example: #define <stdio.h> #define BEG { #define EN } #define NUM int main() BEG NUM n=1; while(n<=5) BEG printf("n is %d",n); n++; EN EN where BEG, EN, NUM are the name of the Macros using #define and },{ and int are the values. after the main() function, BEG is replaced by delimiter "{" and NUM is replaced by int so that
it is of integer type and EN will be replaced by delimiter "}" that is the end of the program.
so this is how macro is works, it replaces the text.

Parametrized Macros

consider an example below of parameterized macros for finding a cube of a number.
In the definition, we use the cube as the name of the macro and after that, we simply
multiply x by 3 times to find cube of a number. so whenever a user is asked to enter the value,
it will find the cube of that number.

C Program To Find Cube of a number using macro

#include<stdio.h>
#define cube(x) x*x*x
int main()
{
   int n;
   printf("Enter a number.\n");
   scanf("%d", &n);
   printf("Cube of %d is %d", n, cube(n));
   return 0;


}
OUTPUT:
Enter a number.
5

Post a Comment

Previous Post Next Post