904 views
3 votes
3 votes
#include<stdio.h>
#define type int
type foo(type b)
{
	return b*b;
}
#undef type
#define type float

int main()
{
	float a = foo(1.1);
	printf("%1.2f", a);
}

 

Please explain line by line execution of this program.

1 Answer

Best answer
10 votes
10 votes

For better understanding the concept behind this question, i changed the question as

 

 

before going to compilation, our source program goes through the preprocessors, at preprocessor stage all macros are substituted in the program.

starts from line 1...  at line 2, preprocessor understood that a macro is defined int as type. ( Simply saying it forms a association between type and int. )

therefore from the line 3 ( in source code ), it simply just replace the the text type with int.

===> line 3 looks as int foo1(int b)

 

at line 7, preprocessor understood that a macro is undefined int as type., it means from here onwards there is no association between type and int.

at line 8, preprocessor understood that a macro is defined float as type. ( Simply saying it forms a association between type and float. )

therefore from the line 9 ( in source code ), it simply just replace the the text type with float.

===> line 9 looks as float foo2(float b)

 

after the phase of preprocessor stage, our code will look like as

 

from here onwards it is very straight forward that

foo1 takes integer as argument ===> variable b of foo1 function value assigned as 1 ===> return (1*1) = 1 ==> stored in the variable a of main function.

foo2 takes float as argument ===> variable b of foo2 function value assigned as 1.1 ===> return (1.1*1.1) = 1.21 ==> stored in the variable b of main function.

edited by

Related questions

2 votes
2 votes
1 answer
1
Hrithik Vashishtha asked Jul 4, 2022
390 views
#include <stdio.h int main () { int i, j; int a [8] = {1, 2, 3, 4, 5, 6, 7, 8}; for(i = 0; i < 3; i++) { a[i] = a[i] + 1; i++; } i ; for (j = 7; j 4; j ) { int i = j/2; ...