Search code examples
cc-preprocessorstring-concatenationstringification

Why does my C program output this?


I am trying to solve two Preprocessor related questions but in both programs I am getting results that I am not able to figure out how. Below is my program:

#include<stdio.h>
#define SQUARE(x) x*x
int main()
{
float s=10,u=30 ,t=2,a;
a=2*(s-u*t)/SQUARE(t);
printf("Result:%f\n",a);
return 0;
}

According to me, the output of this programme should be -25.000 but I am getting -100.000.

And in second program:

#define FUN(i,j) i##j
int main()
{
int val1 = 10;
int val12 = 20;
clrscr();
printf("%d\n",FUN(val1,2));
getch();
}

Output should be 102 but I am getting 20; why is it so?


Solution

  • the first one:

    a=2*(s-u*t)/SQUARE(t);
    

    after replacing the define we get:

    a=2*(s-u*t)/t*t;
    

    now, since we don't have () in the definition of SQUARE we get:

    a=2*(10-30*2)/2*2; --> a=2*(-50)/2*2; --> a=-100/2*2; --> a=-50*2; --> a=-100
    

    if you want to get -25 you should define SQUARE(x) as (x*x).

    Edit : add explanation regarding the second example.

    printf("%d\n"FUN(val1,2));
    

    once again, we first should replace the define (reminder: ## "concatenates" the string of the define - I can't find the perfect words in order to explain it so just take a look at the example...):

    printf("%d\n",val12);  [note: the comma (,) is missing - so it won't compile.]
    

    since the value of val12 is 20 that's what you'll get.

    the point of those 2 examples is to remember that we should always deal with the defines first (since in "real life" the compiler (or pre-processor) does it before the run time)

    I hope it helps..