10. Variable Scoping MCQ

Variable Scoping Question 1

int i;
for (i = 0;i < 5; i++)
  int a = i;
printf("%d", a);
Solution

Variable a is declared inside the for loop and is not accessible outside the loop.

The code snipped throws an error.

Variable Scoping Question 2

Which variable has the longest scope?

#include <stdio.h>
int b;
int main()
{
  int c;
  return 0;
}
int a;
Solution

b. It was declared at the beginning of the program and is valid till the end. c only lives inside main and a is declared at the very end.

So, b has the longest scope.

Variable Scoping Question 3

Choose the correct option

#include <stdio.h> //Program 1
int main()
{
  int a;
  int b;
  int c;
}

#include <stdio.h> //Program 2
int main()
{
  int a;
  {
    int b;
  }
  {
    int c;
  }
}
  1. Both are same

  2. Scope of c is till the end of the main function in Program 2

  3. In Program 1, variables a, b and c can be used anywhere in the main function whereas in Program 2, variables b and c can be used only inside their respective blocks

  4. None of the mentioned

Solution

Option 3 is correct.

Last updated