全局变量和局部变量

// scope.cpp, Maggie Johnson
// Description: A program to illustrate different scopes


#include <iostream>
using namespace std;

//global variables
int a = 18;  
int b = 6;


int function1(int a, int b) {
  return a - b;
}


int function2() {
  int c;
  c = a + b; //
  return c;
}


int main() {

  int b = 12;

  int c = 0;
  cout << ::b << endl; //输出全局变量,::作用域操作符,其左侧为空表明其为全局变量,因为全局作用域本身没有名字,所以作用于操作符左侧为空时代表该变量为全局变量 
  cout << b << endl;   //输出局部变量,即主函数main中定义声明的局部变量b 
  
  cout << a << endl; 
  
  a = function1(b, a); //主函数中没有局部变量a,所以这里使用到的变量a均为全局变量a = 18, 变量b则为主函数中的局部变量b = 12,且最终全局变量a的值变为-6 
  c = function2(); //在没有通过参数列表传参的情况下 C++ 函数使用的是全局变量 ,所以这里函数function2中使用的用到的变量值分别为 a = -6 , b = 6,最终 c = 0 
  cout << "a: " << a << " b: " << b << " c: " << c << endl;
  
  return 0 

}


以下摘自 https://developers.google.com/edu/c++/solutions/1-10

// scope.cpp, Maggie Johnson
// Description: A program to illustrate different scopes

#include <iostream>
using namespace std;

// The following 2 variables are global, that is, they
// are available inside any function in the program.
// If there is a local variable of the same name (either
// a or b) in a function, then the local variable overrides.
// the global.  It is typically not a good idea to use
// global variables, as they can be hard to track.
int a = 18;
int b = 6;

// This function assigns "a" and "b" to the incoming parameters.
// Notice that the local value of b in main is passed in as a,
// and the global value of a is passed in as b.
int function1(int a, int b) {
  return a - b;
}

// This function adds the two global variables, a and b together
// and assigns the sum to a local variable c.  This value is
// returned.  The c variable is no longer available once this
// function has completed its execution.
int function2() {
  int c;
  c = a + b;
  return c;
}

int main (void) {
  // We override the global value of b in this function with
  // this local variable,
  int b = 12;
  // We initialize a variable called c, which is different from
  // the one declared in function 2().
  int c = 0;
  // The global variable a is assigned 12 - 18 = -6 in the next
  // line.
  a = function1(b, a);
  // The local variable c is assigned the sum of the two global
  // variables.  Note that the previous line modified the global
  // variable a, which now equals -6.  Thus, c has the value of
  // -6 + 6 = 0.
  c = function2();
  // We print the value of the global variable a (-6), the local
  // value of b (12), and the local value of c (0).
  cout << "a: " << a << "  b: " << b << "  c: " << c << endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值