Scope and lifetime of variables in and outside funtions — C++ MCQs

30
Score: 0
Attempted: 0/30
1. What is the scope of a local variable in C++?



2. What is the output of the following code?
void fun() { int x = 10; cout << x; }
int main() { fun(); cout << x; }




3. Variables declared inside a function are called:



4. What is the lifetime of a local variable?



5. What will be printed?
int x = 5;
void fun() { int x = 10; cout << x; }
int main() { fun(); }




6. Global variables are declared:



7. What will the code print?
int x = 5;
void fun() { cout << x; }
int main() { fun(); }




8. Which keyword is used to declare a variable that retains its value between function calls?



9. What is the output of the code?
void counter() { static int x = 0; x++; cout << x; }
int main() { counter(); counter(); }




10. What is the scope of a global variable?



11. What will happen if a local and global variable have the same name?



12. What will this program output?
int x = 100;
void display() { int x = 50; cout << x; }
int main() { display(); cout << x; }




13. The lifetime of a global variable is:



14. Which keyword is used to access a global variable hidden by a local variable?



15. What is the output of this code?
int x = 10;
void fun() { int x = 20; cout << ::x; }
int main() { fun(); }




16. What will the following code output?
void test() { static int a = 5; a++; cout << a; }
int main() { test(); test(); test(); }




17. Where is the memory of global variables stored?



18. What will be printed?
void show() { int a = 10; cout << a; }
int main() { show(); show(); }




19. What is the output?
void fun() { static int n = 1; cout << n << " "; n++; }
int main() { fun(); fun(); fun(); }




20. What happens to a local variable after the function ends?



21. Which variable type is visible to all functions in a file?



22. What is the default value of a local variable if not initialized?



23. What is the default value of a global variable if not initialized?



24. What will the code output?
int x;
void fun() { x = 10; }
int main() { fun(); cout << x; }




25. The keyword "extern" is used to:



26. What is the output?
int x = 5;
void fun() { extern int x; cout << x; }
int main() { fun(); }




27. What will be printed?
void fun() { static int x = 1; cout << x; x++; }
int main() { fun(); fun(); fun(); }




28. What is the output of this code?
int a = 5;
void show() { int a = 10; cout << a; }
int main() { cout << a; show(); }




29. Which variable is destroyed only when the program ends?



30. What is the lifetime of a static local variable?



Contents Copyrights Reserved By T4Tutorials