Jan 16, 2012

K & R C Programs Exercise 4-14.

K and R C, Solution to Exercise 4-14:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
Write C Program to swap two arguments using macros.
C Program to swap(t, x, y) that interchanges two arguments of type t using the block structure.

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include <stdio.h>

#define swap(t, x, y) \
  do { \
   t safe ## x ## y; \
   safe ## x ## y = x; \
   x = y; \
   y = safe ## x ## y; \
  } while (0)

int main(void) {
 int inum1, inum2;
 double dnum1, dnum2;
 char *ch1, *ch2;
 printf("\nEnter two Intgers:\n");
 scanf("%d%d",&inum1,&inum2);
 printf("\nIntegers before swap:\n inum1= %d\n inum2= %d\n", inum1, inum2);
 swap(int, inum1, inum2);
 printf("\nIntegers after swap:\n inum1= %d\n inum2= %d\n", inum1, inum2);

 printf("\nEnter two Doubles:\n");
 scanf("%f%f",&dnum1,&dnum2);
 printf("\nDoubles before swap:\n dnum1= %g\n dnum2= %g\n", dnum1, dnum2);
 swap(double, dnum1, dnum2);
 printf("\nDoubles after swap:\n dnum1= %g\n dnum2= %g\n", dnum1, dnum2);

 printf("\nEnter two Strings:\n");
 scanf("%s%s",ch1,ch2);
 printf("\n Strings before swap:\n ch1= %s\n ch2 = %s\n", ch1, ch2);
 swap(char *, ch1, ch2);
 printf("\nStrings after swap:\n ch1= %s\n ch2= %s\n", ch1, ch2);

 return 0;
}
Read more Similar C Programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link