Monday, September 5, 2016

Different variation of #define

1.
#include<stdio.h>
#define SQUARE(t) t*tvoid main()
{
      int n=8, Res;
     Res = 64/SQUARE(t);
     printf("%d",Res);
}
Result will be 64 . why?
because the statement Res=64/SQUARE(t); will be converted to  Res=64/8*8;
Res=64/8*8
     = 8*8=64.
Hence the preprocessor #define only substitute the statement not calculation.
Then what can I do , If I want to result as 1. The program should be
#include<stdio.h>
#define SQUARE(t) (t*t)void main()
{
      int n=8, Res;
     Res = 64/SQUARE(t);
     printf("%d",Res);
}
Now the result will be
Res=64/(8*8)
      =64/64 = 1
Again if program will be
#include<stdio.h>
#define SQUARE(t) (t*t)
void main()
{
      int n=8, Res;
     Res = 81/SQUARE(t+1);
     printf("%d",Res);
}
What will be the result, if you are thing about 1 then it is not right , But why? Now see
Res=81/SQUARE(t+1)
     = 81/(8+1*8+1)
     =81/(8+8+1)
     =81/17
      =4.76
=  4 (Because integer will display only integer part)
then what are the solutions? The solution will be
#include<stdio.h>
#define SQUARE(t) ((t)*(t))void main()
{
      int n=8, Res;
     Res = 81/SQUARE(t+1);
     printf("%d",Res);
}
2. Now guess what will be the result of
#include<stdio.h>
#define CUBE(t) t*t*t
void main()
{
      int n=5, Res;
     Res = 125/CUBE(t);
     printf("%d",Res);
}
???????????????????/
Your queries are always welcome.
3.
#include<stdio.h>
#define print(Num) printf("%d",Num);
int main()
{
    int Number=10;
    print(Number);
    return 1;
 }
It will display 10 , So Now you can print integer variable by own print command
4.


No comments:

Post a Comment