0
0
Cprogramming~20 mins

Lifetime and scope comparison - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Lifetime and Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
}
A10 10
B5 10
C10 5
D5 5
Attempts:
2 left
💡 Hint
Remember that variables declared inside a block have their own scope.
Predict Output
intermediate
2: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;
}
A1 2 3
B0 1 2
C1 1 1
D3 3 3
Attempts:
2 left
💡 Hint
Static variables keep their value between function calls.
🔧 Debug
advanced
2: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;
}
ARuntime error: segmentation fault or undefined behavior
BCompilation error: returning address of local variable
COutput: 10
DCompilation warning but runs and prints 0
Attempts:
2 left
💡 Hint
Think about the lifetime of local variables after the function returns.
🧠 Conceptual
advanced
2: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;
}
AAll have static lifetime
Bglobal_var
Clocal_var
Dstatic_var
Attempts:
2 left
💡 Hint
Global variables exist for the whole program run.
Predict Output
expert
2: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;
}
A
0 1
1 1
2 1
B
1 1
1 1
1 1
C
1 0
2 0
3 0
D
1 1
2 1
3 1
Attempts:
2 left
💡 Hint
Static variables keep their value between calls; automatic variables reset each call.