Write a C program to add two numbers using macros. How to add two numbers using macros #define
preprocessor directive in C program. Logic to add two numbers using macros.
In previous post we learned basics about macros. How to define, undefine and redefine a macro in C programming. Here we will continue from our last lesson. We will learn how we can use macros to solve basic programming requirements.
In this post we will learn to add two numbers using macros.
Required knowledge
Read more how to find sum of two numbers using functions?
How to add two numbers using macros?
In previous post we talked about defining constants using a macro. However, you can even transform a small function to a macro. Macros execute before compilation of your program hence are super fast than normal functions. Hence, always try to convert your small functions that does not contain any complex logic to macros.
Let us define a macro that accepts two parameters and return sum of given numbers.
Syntax:
#define MACRO_NAME(params) MACRO_BODY
Where MACRO_NAME
is name of the macro. params
is parameters passed to macro. MACRO_BODY
is the body where we will write actual logic of macro.
Example:
#define SUM(x, y) (x + y)
Program to add two numbers using macro
/**
* C program to add two numbers using macros
*/
#include <stdio.h>
// Define macro to find sum of two numbers
#define SUM(x, y) (x + y)
int main()
{
int num1, num2;
// Input two numbers from user
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
// Calculate and print sum using macro
printf("Sum(%d, %d) = %d\n", num1, num2, SUM(num1, num2));
return 0;
}
Output
Enter any two numbers: 10 20 Sum(10, 20) = 30
Happy coding 😉