Write a C program to swap two numbers utilizing macro. How swap two numbers with out utilizing third variable utilizing macro in C program. Logic to swap two quantity with out utilizing third variable utilizing macro.
Swapping values of two variables is a typical downside. We already mentioned a number of methods to swap two variables all through the course of C programming tutorial.
Be taught other ways to swap
On this publish we are going to proceed our macro train. Right here I’ll clarify how one can rework swapping logic to macro.
Required data
Primary C programming, Macros, Bitwise operator
Find out how to swap two numbers utilizing macro
Earlier than shifting forward, I assume that you’re conscious with macro syntax, outline and use.
For this publish I’ll swap two numbers with out utilizing third variable. I’ll make use of bitwise operator. When you’ve got any associated to bitwise operator logic please learn swap two numbers utilizing bitwise operator.
Allow us to get began and outline a macro that accepts two arguments say SWAP(x, y)
. The macro will swap the values of x
and y
.
Instance:
#outline SWAP(x, y) (x ^= y ^= x)
Program to swap two numbers utilizing macro
/**
* C program to swap two numbers utilizing macro
*/
#embody <stdio.h>
// Outline macro to swap two numbers
#outline SWAP(x, y) (x ^= y ^= x ^= y)
int foremost()
{
int num1, num2;
// Enter two numbers from customers
printf("Enter any two quantity to swap: ");
scanf("%dpercentd", &num1, &num2);
printf("Values earlier than swappingn");
printf("num1 = %d, num2 = %dnn", num1, num2);
SWAP(num1, num2);
printf("Values after swappingn");
printf("num1 = %d, num2 = %dn", num1, num2);
return 0;
}
Learn extra
Enter any two quantity to swap: 10 20 Values earlier than swapping num1 = 10, num2 = 20 Values after swapping num1 = 20, num2 = 10
Glad coding 😉