Govt. Exams
Entrance Exams
#define SIZE 10
#define SIZE 20
Redefining a macro with a different value in the same compilation unit causes a compilation error. To redefine, you must #undef first.
#define RECURSE() RECURSE()
The C preprocessor does not detect or prevent recursive macro expansion in its definition. RECURSE() will expand to RECURSE() infinitely, causing the preprocessor to hang or run out of memory. Modern compilers have safeguards, but theoretically this creates infinite expansion.
#define MAX(a,b) ((a)>(b)?(a):(b))
int main() { printf("%d", MAX(5++, 10)); return 0; }
The macro expands to ((5++)>(10)?(5++):(10)). The variable 5++ is evaluated multiple times due to macro substitution, causing undefined behavior. Increment operations in macro arguments should be avoided. This highlights why inline functions or constexpr functions are preferred in modern C++.
#define VERSION "2024"
#define STR(x) #x
printf(STR(VERSION));
Stringification happens before macro expansion of arguments. STR(VERSION) becomes "VERSION" (a string literal of the token VERSION), not the value of VERSION. To stringify the expanded value, use indirect stringification with two levels of macros.
If used in an if-else without braces, which problem occurs?
if(condition) SWAP(x,y); else printf("No swap");
The macro expands to {int temp=a; a=b; b=temp;}; which ends with a semicolon. This creates: if(condition) {...}; else... The semicolon after the block makes else unreachable. The macro should use do-while(0) wrapper or be wrapped in a function.
C99 variadic macros don't have a built-in way to count arguments. Option A uses a clever technique with array size calculation. Option B references non-standard VA_NARGS. Options C and D use invalid syntax with token pasting.
What is the issue and how to fix it?
Without parentheses, AREA(2+1) becomes 3.14*2+1*2+1 = 11.28. Proper version: #define AREA(r) (3.14*((r))*((r))) protects argument evaluation.
Macros are textual replacements that happen before compilation. If a macro has the same name as a library function, the macro replaces all occurrences of that name.
#define SWAP(a,b) {int temp=a; a=b; b=temp;}
What issue might occur with this macro?
While the macro works for all types (a and b are copied), the curly braces can cause issues when used in if-else statements without proper syntax (like missing semicolon after if). Additionally, it's limited to specific types. The safest answer is D regarding syntactic issues with placement.
A dangling macro typically refers to a macro that is defined but its usage may cause issues. More accurately, it's when a macro's scope or definition is unclear, especially in conditional compilation scenarios where #undef might cause problems.