What are local and global variables and their differences? - www.studyandupdates.com

Monday

What are local and global variables and their differences?

Q 17. What are local and global variables and their differences?

Ans :

  • Global Variable:

Global variables are variables that are defined outside of functions. These variables have global scope, so they can be used by any function without passing them to the function as parameters.

  • Local Variable:

Local variables are variables that are defined within functions. They have local scope, which means that they can only be used within the functions that define them.


Global VariableLocal Variable
Global variables are declared outside all the function blocks.Local Variables are declared within a function block.
The scope remains throughout the program.The scope is limited and remains within the function only in which they are declared.
Any change in global variable affects the whole program, wherever it is being used.Any change in the local variable does not affect other functions of the program.
A global variable exists in the program for the entire time the program is executed.A local variable is created when the function is executed, and once the execution is finished, the variable is destroyed.
It can be accessed throughout the program by all the functions present in the program.It can only be accessed by the function statements in which it is declared and not by the other functions.
If the global variable is not initialized, it takes zero by default.If the local variable is not initialized, it takes the garbage value by default.
Global variables are stored in the data segment of memory.Local variables are stored in a stack in memory.
We cannot declare many variables with the same name.We can declare various variables with the same name but in other functions.








No comments:

Post a Comment

Popular Posts