Govt Exams
#define STR(x) #x
int main() { printf("%s", STR(Hello)); return 0; }
The # operator converts the macro argument into a string literal. STR(Hello) becomes "Hello", and printf outputs Hello without quotes.
The ## operator concatenates two tokens into one. For example, #define CONCAT(a,b) a##b creates CONCAT(hello, world) → helloworld.
Option C using do-while(0) is the safest approach to avoid issues with semicolons in if-else statements. Option B can cause problems with control flow statements.
#define SQUARE(x) x*x
int main() { int a = SQUARE(2+3); printf("%d", a); return 0; }
SQUARE(2+3) expands to 2+3*2+3 = 2+6+3 = 11 due to operator precedence. Proper macro should use parentheses: #define SQUARE(x) ((x)*(x))
#define PI 3.14
int main() { printf("%f", PI); return 0; }
PI is replaced by 3.14 during preprocessing. When printed with %f format specifier, it displays as 3.140000 (default 6 decimal places).
#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.
__LINE__ expands to the current line number and __FILE__ expands to the current filename. These are predefined macros that provide compile-time information useful for debugging and error reporting.
Option A uses #ifdef to check if DEBUG is defined, which is correct for conditional compilation. Option B would check if DEBUG has a non-zero value (expression-based). Options C and D have invalid syntax.
#define SIZE 10
int arr[SIZE];
#undef SIZE
int arr2[SIZE];
After #undef SIZE, the macro SIZE is no longer defined. Attempting to use SIZE in int arr2[SIZE] will cause a compilation error because SIZE is not recognized by the compiler.
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.