Local variable and Global variable

Variable Scope

In variable chapter you have read about variable. There are two type of variable according to scope:
(1.) Local variable
(2.) Global variable


Local variable

A variable which is declared inside of function or block that is called "Local variable". Local variable can not be used outside of function or block. In below program a and b variable declared inside of f1() therefore a and b is local variable.

See Output

See Output

In above program has an error and warning . In above program uses f1() and f2() function. Inside of f1() two variables is declared therefor a and b variable are local variable.

But f2() wants to use b variable therefore program has an error because local variable can not be use outside of function or block.


See Output

In above program uses m variable which is declared inside of if(){ } block therefore m is local variable.


See Output

In above program has error. f1() uses an if(){ } block. m varible is decalred inside of if(){ } block therefore m is a local variable.

But program uses m variable outside of if(){ } block therefore program has error because m variable can not be use outside of if(){ } block.


See Output

parameter of a function is also called local variable. Therefore parameters can not be used outside of function.


Global Variable

Global variable is always declared outside of function body. Global variable can be use anywhere in program.

In below program n is declared outside of function therefore n is a global variable and global variable is used anywhere in program.

See Output

Variable priority

Local variable and Global variable both are with same name then local variable priority is higher than global variable.

See Output

About Us

Comsysapp.com is an educational website. Students and software developers can learn programming language tutorials. Comsysapp is very useful for beginners and professional developers. Comsysapp provides tutorial in easy language. Comsysapp.com has focus on simplicity.

Services

Comsysapp.com provides free tutorials like c, html, css, etc. All tutorials are free for beginner and professionals.


Terms of Use

comsysapp.com is not responsible for any mistake. We are not responsible if information made available on our website is incomplete or invalid. But comsysapp.com always try for zero-zero mistake.

Privacy policy

comsysapp.com does not collect any data from users. We use Google AdSense advertising on our website. We never ask personal or private information.


Sitemap

sitemap

copyright © 2023