Variable Scope in C++

A scope is a region of the program and broadly speaking there are three places, where variables can be declared −

  • Inside a function or a block which is called local variables,

  • In the definition of function parameters which is called formal parameters.

  • Outside of all functions which is called global variables.

We will learn what is a function and it's parameter in subsequent chapters. Here let us explain what are local and global variables.

Local Variables

Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code.

Local variables are not known to functions outside their own. Following is the example using local variables −

#include <iostream>
using namespace std; int main () { // Local variable declaration: int a, b; int c; // actual initialization a = 10; b = 20; c = a + b; cout << c; return 0; }

Global Variables

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.

Following is the example using global and local variables −

 

#include <iostream>
using namespace std; // Global variable declaration: int g; int main () { // Local variable declaration: int a, b; // actual initialization a = 10; b = 20; g = a + b; cout << g; return 0; }

A program can have same name for local and global variables but value of local variable inside a function will take preference. For example −

Initializing Local and Global Variables

 

int     0
char '\0'
pointer NULL

https://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm

转载于:https://www.cnblogs.com/poission/p/10867474.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值