Challenge - 5 Problems
Lifetime and Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of variable with block scope
What is the output of this C program?
C
#include <stdio.h> int main() { int x = 5; { int x = 10; printf("%d ", x); } printf("%d\n", x); return 0; }
Attempts:
2 left
💡 Hint
Remember that variables declared inside a block have their own scope.
✗ Incorrect
The inner block declares a new variable x that shadows the outer x. Inside the block, x is 10. Outside, it is 5.
❓ Predict Output
intermediate2:00remaining
Output of static variable in function
What is the output of this C program?
C
#include <stdio.h> void counter() { static int count = 0; count++; printf("%d ", count); } int main() { counter(); counter(); counter(); return 0; }
Attempts:
2 left
💡 Hint
Static variables keep their value between function calls.
✗ Incorrect
The static variable count is initialized once and keeps incrementing each call, so outputs 1, 2, 3.
🔧 Debug
advanced2:00remaining
Identify the error with variable lifetime
What error will this C code produce when compiled or run?
C
#include <stdio.h> int* getPointer() { int x = 10; return &x; } int main() { int* p = getPointer(); printf("%d\n", *p); return 0; }
Attempts:
2 left
💡 Hint
Think about the lifetime of local variables after the function returns.
✗ Incorrect
The function returns address of a local variable which is destroyed after return. Using it causes undefined behavior, often a runtime crash.
🧠 Conceptual
advanced2:00remaining
Which variable has static lifetime?
Given these variable declarations, which one has static lifetime and global scope?
C
int global_var; void func() { static int static_var = 0; int local_var = 0; }
Attempts:
2 left
💡 Hint
Global variables exist for the whole program run.
✗ Incorrect
Global variables have static lifetime. Static local variables also have static lifetime but limited scope. Local variables have automatic lifetime.
❓ Predict Output
expert2:00remaining
Output of nested static and automatic variables
What is the output of this C program?
C
#include <stdio.h> void f() { static int s = 0; int a = 0; s++; a++; printf("%d %d\n", s, a); } int main() { f(); f(); f(); return 0; }
Attempts:
2 left
💡 Hint
Static variables keep their value between calls; automatic variables reset each call.
✗ Incorrect
Static variable s increments and keeps value across calls. Automatic variable a resets to 0 each call then increments to 1.