博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Variable Scope in C++
阅读量:5932 次
发布时间:2019-06-19

本文共 1863 字,大约阅读时间需要 6 分钟。

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 
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 
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

你可能感兴趣的文章
git使用详解
查看>>
Struts2(接受表单参数)请求数据自动封装和数据类型转换
查看>>
08:石头剪刀布
查看>>
【SAP HANA】新建账户和数据库(2)
查看>>
Rsync服务介绍与配置
查看>>
JQuery获取浏览器窗口的可视区域高度和宽度,滚动条高度
查看>>
CentOS 6.4下编译安装MySQL 5.6.14 (转)
查看>>
在同一台电脑上添加多个ssh key
查看>>
直方图、基数、选择性、群集因子
查看>>
ASP.NET Web API身份验证和授权
查看>>
dbcp 详细配置
查看>>
如何定义StrokeIt手势 常用StrokeIt手势大全
查看>>
LCA 最近公共祖先
查看>>
23种设计模式之工厂方法
查看>>
Docker
查看>>
Java笔记4:JDBC纯驱动方式连接Oracle
查看>>
java 内部类、匿名内部类、嵌套类的使用
查看>>
Scala使用Akka模拟RPC机制代码
查看>>
Linux下使用Fastboot给手机刷ROM
查看>>
怎样在tsung中使用动态參数(二)
查看>>