Here is a listing of C questions and puzzles on “Macro Substitution” along with answers, explanations and/or solutions:
1. What will be the output of the following C code?
-
#include
-
#define foo(m, n) m ## n
-
int main()
-
{
-
printf("%sn", foo(k, l));
-
}
a) k l
b) kl
c) Compile time error
d) Undefined behaviour
Answer: c
Clarification: None.
2. What will be the output of the following C code?
-
#include
-
#define foo(m, n) " m ## n "
-
int main()
-
{
-
printf("%sn", foo(k, l));
-
}
a) k l
b) kl
c) Compile time error
d) m ## n
Answer: d
Clarification: None.
3. What will be the output of the following C code?
-
#include
-
#define foo(x, y) #x #y
-
int main()
-
{
-
printf("%sn", foo(k, l));
-
return 0;
-
}
a) kl
b) k l
c) xy
d) Compile time error
Answer: a
Clarification: None.
4. What will be the output of the following C code?
-
#include
-
#define foo(x, y) x / y + x
-
int main()
-
{
-
int i = -6, j = 3;
-
printf("%dn",foo(i + j, 3));
-
return 0;
-
}
a) Divided by zero exception
b) Compile time error
c) -8
d) -4
Answer: c
Clarification: None.
5. What will be the output of the following C code?
-
#include
-
void f();
-
int main()
-
{
-
#define foo(x, y) x / y + x
-
f();
-
}
-
void f()
-
{
-
printf("%dn", foo(-3, 3));
-
}
a) -8
b) -4
c) Compile time error
d) Undefined behaviour
Answer: b
Clarification: None.
6. What will be the output of the following C code?
-
#include
-
void f();
-
int main()
-
{
-
#define max 10
-
f();
-
return 0;
-
}
-
void f()
-
{
-
printf("%dn", max * 10);
-
}
a) 100
b) Compile time error since #define cannot be inside functions
c) Compile time error since max is not visible in f()
d) Undefined behaviour
Answer: a
Clarification: None.
7. What will be the output of the following C code?
-
#include
-
#define foo(x, y) x / y + x
-
int main()
-
{
-
int i = -6, j = 3;
-
printf("%d ", foo(i + j, 3));
-
printf("%dn", foo(-3, 3));
-
return 0;
-
}
a) -8 -4
b) -4 divided by zero exception
c) -4 -4
d) Divided by zero exception
Answer: a
Clarification: None.
8. What will be the output of the following C code?
-
#include
-
int foo(int, int);
-
#define foo(x, y) x / y + x
-
int main()
-
{
-
int i = -6, j = 3;
-
printf("%d ",foo(i + j, 3));
-
#undef foo
-
printf("%dn",foo(i + j, 3));
-
}
-
int foo(int x, int y)
-
{
-
return x / y + x;
-
}
a) -8 -4
b) Compile time error
c) -8 -8
d) Undefined behaviour
Answer: a
Clarification: None.
9. What is the advantage of #define over const?
a) Data type is flexible
b) Can have a pointer
c) Reduction in the size of the program
d) None of the mentioned
Answer: a
Clarification: None.