0
0
Cprogramming~20 mins

Scope of variables - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of variable shadowing in nested blocks

What is the output of this C code?

C
#include <stdio.h>

int main() {
    int x = 5;
    {
        int x = 10;
        printf("%d\n", x);
    }
    printf("%d\n", x);
    return 0;
}
A10\n10\n
B10\n5\n
C5\n10\n
D5\n5\n
Attempts:
2 left
💡 Hint

Remember that inner blocks can have variables with the same name that hide outer ones.

Predict Output
intermediate
2:00remaining
Output of static variable inside function

What will be printed when this program runs?

C
#include <stdio.h>

void counter() {
    static int count = 0;
    count++;
    printf("%d ", count);
}

int main() {
    counter();
    counter();
    counter();
    return 0;
}
A0 0 0
B0 1 2
C1 2 3
D1 1 1
Attempts:
2 left
💡 Hint

Static variables inside functions keep their value between calls.

Predict Output
advanced
2:00remaining
Output of global and local variable with same name

What is the output of this program?

C
#include <stdio.h>

int val = 100;

void printVal() {
    int val = 50;
    printf("%d ", val);
}

int main() {
    printVal();
    printf("%d\n", val);
    return 0;
}
A50 100\n
B100 50\n
C50 50\n
D100 100\n
Attempts:
2 left
💡 Hint

Local variables hide global variables inside their scope.

Predict Output
advanced
2:00remaining
Output of uninitialized local variable

What will this program print?

C
#include <stdio.h>

int main() {
    int x;
    printf("%d\n", x);
    return 0;
}
AUndefined value (garbage) printed
B0
CCompilation error due to uninitialized variable
DRuntime error
Attempts:
2 left
💡 Hint

Local variables are not automatically set to zero.

Predict Output
expert
3:00remaining
Output of variable scope with extern and static

Given these two files, what is the output when compiled and run together?

file1.c

#include 

static int count = 5;

void printCount() {
    printf("%d\n", count);
}

file2.c

#include 

extern int count;

int main() {
    printCount();
    printf("%d\n", count);
    return 0;
}
A0\n0\n
B5\n5\n
CLinker error\n
D5\nLinker error\n
Attempts:
2 left
💡 Hint

Static variables have internal linkage and are not visible outside their file.