Why does my C program output this?

I am trying to solve two issues related to the preprocessor, but in both programs I get results that I can not understand. 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;
}

For me, the output of this program should be -25.000, but I get -100.000.

And in the second program:

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

There should be a way out 102, but I get it 20; why is that so?

+3
source share
4 answers

the first:

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

after replacing the definition we get:

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

since in the definition of SQUARE we do not have ():

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 receive -25, you must determine SQUARE(x)how (x*x).

Edit: Add clarification to the second example.

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

, define (reminder: ## "concatenates" - , , ... ):

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

val12 20, .

, , ( " " ( ) )

, .

+4
#define SQUARE(x) x*x

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

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

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

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

, FUN(val1,2) val12 ##. , : printf

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

20.

+11

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

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

. , .

+3

, , .

# at define ,

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

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

tom = india, tom #.

## , .

va1 2. j. va1 2 . va12.

va12 is an identifier available with a value of 20. therefore 20 is returned.

0
source

All Articles