适用范围VS在C变量的生命 [英] Scope vs life of variable in C

查看:99
本文介绍了适用范围VS在C变量的生命的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释不清楚的C.变量​​的作用域和生命的概念是它在C ++中有什么不同?我的范围和生活之间的混淆。

Could someone exactly explain the concept of scope and life of variable in C. Is it different in C++? I'm confused between scope and life.

推荐答案

范围是其中变量是可以访问的区域。结果
续航时间在此期间,对象保持有效的时间跨度。

Scope is the region where the variable is accessible.
Life time is the time span during which an object remains valid.

这是简单的例子:

#include <iostream.h>

void doSomething()
{
    x = 5; //Error! Not Accessible
}

int main() 
{

      int x = 4;
      std::cout<< x << endl;
      {
            int x = 2;
            cout << x << endl;
      }
      doSomething(); 
      std::cout<< x << endl;
      return 0;
}

以上给出的输出:

The above gives the output:

4结果
  2结果
  4

4
2
4

在上面的程序,结果
变量的寿命X = 4 是整个主,即:它在整个主的执行仍然活着,而且这是在主要的访问,这是它的范围。注意,这不是在功能访问,因为它超出了变量的范围 X

In above program,
lifetime of variable x = 4 is throughout the main, i.e: It remains alive throughout the execution of the main, Also it is accessible within the main, that is its scope. Note that it is not accessible in the function because it is beyond the scope of the variable x.

而范围和变量的生存期 X = 2 是enclsing括号内 { } 主内。

while scope and lifetime of variable x = 2 is within the enclsing braces{ } inside the main.

这篇关于适用范围VS在C变量的生命的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆