Friday, August 29, 2014

preprocessor macros


Token Pasting (##)

combine two different tokens into single token in macro definition
Example


#include <stdio.h>

#define tokenpaster(n) printf ("token" #n " = %d", token##n)

int main(void)
{
   int token34 = 40;
   
   tokenpaster(34);
   return 0;
}
output:
token34=40


#include <stdio.h>
#define merge(a, b) a##b
int main()
{
    printf("%d ", merge(12, 34));
}
// Output: 1234
// here if you use sprintf then that it can be used for another purpose

Stringize (#)


  • converts the macro parameters into string constant
  • A token passed to macro can be converted to a sting literal by using # before it.


#include <stdio.h>

#define  message_for(a, b)  \
    printf(#a " and " #b ": We love you!\n")

int main(void)
{
   message_for(Carole, Debra);
   return 0;
}
 
output:
Carole and Debra: We love you!


Purpose of using do-while in the multiline macro:






#define just do the copy and not doing any evaluations:


  • at first look it gives output like 1 but see carefully


example:


#define square(x) x*x
int main()
{
  int x = 36/square(6); // Expended as 36/6*6
  printf("%d", x);
  return 0;
}
// Output: 36
#include <stdio.h>
#define MULTIPLY(a, b) a*b
int main()
{
    // The macro is expended as 2 + 3 * 3 + 5, not as 5*8
    printf("%d", MULTIPLY(2+3, 3+5));
    return 0;
}
// Output: 16

to know interesting fact about macro please refer:
http://www.geeksforgeeks.org/interesting-facts-preprocessors-c/



Reference:
http://www.tutorialspoint.com/cprogramming/c_recursion.htm

No comments:

Post a Comment