Why does my C program output this?

2.2k views Asked by At

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?

4

There are 4 answers

5
SivGo On BEST ANSWER

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..

4
Alexandre C. On
#define SQUARE(x) x*x

should be

#define SQUARE(x) ((x)*(x))

Indeed, without the parentheses, 2*(s-u*t)/SQUARE(t) is expanded as

2*(s-u*t)/t*t

which is interpreted as

(2*(s-u*t)/t)*t

As to your second problem, FUN(val1,2) will get expanded as val12 per the semantics of the ## operator. It is still not clear what your intent is: the printf line will be understood as

printf("%d\n", val12);

which will print 20.

0
Shamim Hafiz - MSFT On

For the first case,

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

would translate to

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

at compile time. This is a common mistake made with preprocessors.

0
selvabharathi s On

i know i am late, but i am having the perfect answer.

in c # at define is used to call the text as it is in the function parameter,

example, #define hai(s1) printf("%s=%s",#s1,s1);

       in main: i am calling as hai(tom); tom was initialized as "india" string.

the output for this is tom=india, the calling string tom is printed by help of #.

similarly ## is used to take the text from function argument and join them and return the value of the joined identifier.

the above program has two argument va1 and 2. passed to i and j. then va1 and 2 is joined. and form va12.

va12 is the identifier available with value 20. that's why 20 is returned.