Write a program to Swap to number using micro in c

28 Dec 2022 Balmiki Mandal 0 C Programming

C Program to Swap Two Numbers Using a Macro

Write a program to Swap two numbers using a macro in C" means that you need to write a C program that defines a macro to swap the values of two variables.

A macro is a piece of code that is defined using the #define directive and can be used to replace a particular sequence of code with another sequence of code during compilation. In this case, you need to define a macro that takes two arguments (two variables) and swaps their values.

Example 01 is to demonstrate how to use macros in C and how they can be used to simplify repetitive or complex code.

#include <stdio.h>
#define SWAP(x, y) { \
    typeof(x) temp = x; \
    x = y; \
    y = temp; \
}

int main() {
    int a = 10, b = 20;
    printf("Before swapping: a = %d, b = %d\n", a, b);
    SWAP(a, b);
    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}

In the above program, the SWAP macro is defined using the curly braces {} to create a block of code that performs the swapping. It uses the typeof keyword to declare a temporary variable of the same type as the first argument passed to the macro. The macro then assigns the value of the first argument to the temporary variable, assigns the value of the second argument to the first argument, and finally assigns the value of the temporary variable to the second argument.

In the main function, we declare two integer variables a and b and assign them the values 10 and 20 respectively. We then print out the values of a and b before swapping, call the SWAP macro to swap the values of a and b, and print out the values of a and b after swapping.

When you run the program, the output should be:

Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10

 

Example 02 Swap to numbers using micro 

#include<stdio.h>
#define swap(a,b,type) {type t;\
t=a;\
a=b;\
b=t;}
void main()
{
    int i=10,j=20;
    printf("before: i=%d j=%d\n",i,j);
    swap(i,j,int);//micro call for integer
    printf("after i=%d j=%d\n",i,j);

    float f=23.5,f1=33.5;
    printf("before: f=%f f1=%f\n",f,f1);
    swap(f,f1,float);//micro call for floating value
    printf("after: f=%f f1=%f\n",f,f1);
 

Output:

before: i=10 j=20
after i=20 j=10
before: f=23.500000 f1=33.500000
after: f=33.500000 f1=23.500000

Conclusion:

//#define is preprocessor unit
//swap(a,b,type) micro name
//{type t;\
     t=a;\
     a=b;\
     b=t;}micro body

 

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.