Challenge - 5 Problems
Static Storage Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ 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() { for(int i = 0; i < 3; i++) { counter(); } return 0; }
Attempts:
2 left
💡 Hint
Remember that static variables inside functions keep their value between calls.
✗ Incorrect
The static variable 'count' is initialized only once and retains its value between function calls, so it increments each time the function is called.
❓ Predict Output
intermediate2:00remaining
Static variable scope in multiple files
Given two files, what will be the output when compiled and run together?
File1.c:
#include
static int x = 5;
void printX() {
printf("%d\n", x);
}
File2.c:
extern void printX();
int main() {
printX();
return 0;
}
Attempts:
2 left
💡 Hint
Static variables have internal linkage, but functions can access them within the same file.
✗ Incorrect
The static variable 'x' is only visible inside File1.c, but the function printX() can access it and print 5. The main calls printX(), so output is 5.
🔧 Debug
advanced2:00remaining
Why does this static variable reset unexpectedly?
Consider this code snippet:
#include
void func() {
static int val = 10;
printf("%d ", val);
val = 5;
}
int main() {
func();
func();
return 0;
}
What is the output and why?
Attempts:
2 left
💡 Hint
Static variables keep their value between calls, but you are changing it inside the function.
✗ Incorrect
The static variable 'val' is initialized once to 10. The first call prints 10 and sets val to 5. The second call prints 5 because val retains the changed value.
📝 Syntax
advanced2:00remaining
Identify the syntax error with static variable usage
Which option contains a syntax error related to static variable declaration?
C
void example() { static int a = 0; a++; }
Attempts:
2 left
💡 Hint
Look for missing semicolons in the declarations described in the options.
✗ Incorrect
Option C describes 'static int a = 0 inside a function without semicolon', which lacks a semicolon after the declaration and is a syntax error. The other options describe valid syntax.
🚀 Application
expert2:00remaining
How many times is the static variable initialized?
Analyze this code:
#include
void test() {
static int x = 0;
printf("%d ", x);
x++;
}
int main() {
for(int i = 0; i < 4; i++) {
test();
}
return 0;
}
How many times is the static variable 'x' initialized during the program execution?
Attempts:
2 left
💡 Hint
Static variables inside functions are initialized only once, not every call.
✗ Incorrect
The static variable 'x' inside test() is initialized only once before the first call to test(). It keeps its value between calls.