Chapter - 8: The C Preprocessor

What would be the output of the following program:


B
Sections
1
Exercises

A

B

C

1

(a)

#include<stdio.h>
int main()
{
	int i = 2;
#ifdef DEF
	i *= i;
#else
	printf("\n%d", i);
#endif
	return 0;
}

Output: 2

Because DEF is not defined in the program, so else condition will
execute and the value of i is printed.


(b)

#include<stdio.h>
#define PRODUCT(x) (x*x)
int main()
{
	int i = 3, j, k;
	j = PRODUCT(i++);
	k = PRODUCT(++i);

	printf("\n%d %d", j, k);
	return 0;
}

Output: 9 49

Because the macro is expanded as
i++*i++ = 3++*3++ = 9 (post increment operator).
++i*++i = ++5*++5 = 7*7 = 49 (pre increment operator).


(c)

#include<stdio.h>
#define PI 3.14
#define AREA(x,y,z) PI*x*x+y*z

int main()
{
	float a = AREA(1, 5, 8);
	float b = AREA(AREA(1, 5, 8), 4, 5);
	printf("a = %f\n", a);
	printf("b = %f\n", b);
	return 0;
}

Output:
a = 43.14
b = 5863.727051

Because second statement is expand as
(PI*AREA(1,5,8)*AREA(1,5,8) + 4*5)
(PI*(PI*1*1+5*8)*(PI*1*1+5*8)+4*5) = 3.14*43.14*43.14+4*5 = 5863.727


© 2020 Garbage Valuegarbage value logo