0
0
C++programming~10 mins

Scope of variables in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a variable inside the main function.

C++
int main() {
    int [1] = 10;
    return 0;
}
Drag options to blanks, or click blank then click option'
Anumber
Bcout
Cmain
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using a keyword as a variable name.
Using function names as variable names.
2fill in blank
medium

Complete the code to print the value of the local variable inside the function.

C++
#include <iostream>
using namespace std;

void show() {
    int x = 5;
    cout << [1] << endl;
}

int main() {
    show();
    return 0;
}
Drag options to blanks, or click blank then click option'
Ax
By
Cz
Dcout
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to print a variable not declared in the function.
Using variable names not declared anywhere.
3fill in blank
hard

Fix the error by completing the code to access the global variable inside the function.

C++
#include <iostream>
using namespace std;

int [1] = 100;

void printGlobal() {
    cout << [1] << endl;
}

int main() {
    printGlobal();
    return 0;
}
Drag options to blanks, or click blank then click option'
Anum
Bvalue
Cx
DglobalVar
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the global variable declaration and usage.
Trying to access a variable not declared globally.
4fill in blank
hard

Fill both blanks to declare a variable inside a block and print it.

C++
#include <iostream>
using namespace std;

int main() {
    {
        int [1] = 20;
        cout << [2] << endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
AblockVar
CmainVar
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for declaration and printing.
Trying to access the variable outside the block.
5fill in blank
hard

Fill all three blanks to declare a global variable, shadow it inside main, and print both values.

C++
#include <iostream>
using namespace std;

int [1] = 50;

int main() {
    int [2] = 100;
    cout << ::[3] << endl; // global
    cout << [2] << endl; // local
    return 0;
}
Drag options to blanks, or click blank then click option'
Acount
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for global and local variables.
Not using :: to access the global variable inside main.