ProgrammingHardWipro · Cognizant pattern
What is printed? (Assume no overflow trapping.)
What is printed? (Assume no overflow trapping.)
int f(int n) {
if (n == 0) return 0;
return n + f(n - 1);
}
int main(void) {
printf("%d", f(100000));
}- A. Compilation error: recursion depth must be a compile-time constant
- B. It prints the correctly computed sum 5000050000
- C. Stack overflow / undefined behaviour / crash, due to 100000 nested stack frames
- D. It prints 0 because the recursion depth exceeds INT_MAX
Correct answer: C. Stack overflow / undefined behaviour / crash, due to 100000 nested stack frames
Each recursive call adds a new stack frame; with no tail-call optimisation guaranteed by the C standard (and this isn't in tail position anyway, since `n +` happens after the call returns), 100,000 nested frames will typically exhaust the call stack, causing a crash — this is undefined behaviour from stack exhaustion, not a computed answer.
More C Programming questions
- What is printed? c int mystery(int a, int b) { if (b == 0) return a; return mystery(b, a % b); } int main(void) { printf("%d", mystery(48…
- What is printed? (Assume int is 32 bits, two's complement.) c unsigned int a = 0xF0F0F0F0; unsigned int b = a >> 4; printf("%X", b);
- What is printed? (Assume int is 32 bits, two's complement, arithmetic right shift for signed negatives — the common but…
- What is printed? (Check if a number is a power of two.) c int isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } int main(void) {…
- What is printed? c int swaptrick(int a, int b) { a = a ^ b; b = a ^ b; a = a ^ b; printf("%d %d ", a, b); return a + b; } int main(void) {…
- What is printed? c #define SETBIT(x, n) ((x) | (1 << (n))) #define CLEARBIT(x, n) ((x) & ~(1 << (n))) #define TOGGLEBIT(x, n) ((x) ^ (1 <<…