加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在控制结构块中定义变量

发布时间:2020-12-16 07:30:43 所属栏目:百科 来源:网络整理
导读:如果我在控制结构的块中定义一个变量,它是否仅存在于该控制结构块的执行中而不存在于封闭函数的整个执行中? 另外,我如何监视程序的确切内存使用情况及其变化(即:通过创建和销毁变量来改变内存使用情况)? 后来添加: 在下面的代码中,我知道v scope是if blo
如果我在控制结构的块中定义一个变量,它是否仅存在于该控制结构块的执行中而不存在于封闭函数的整个执行中?

另外,我如何监视程序的确切内存使用情况及其变化(即:通过创建和销毁变量来改变内存使用情况)?

后来添加:
在下面的代码中,我知道v scope是if block,但是我想知道在if块的开始/结束或函数func的开始/结束时是否在内存中创建/销毁了v?

void func ()
{
    if (true)
    {
        int v;//automatic storage class
        v = 1;
    }
}

解决方法

If I define a variable inside the block of a control structure,does it exist only in the execution of that control structure’s block and not in the whole execution of the enclosing function?

这取决于您声明变量的位置而不是定义它.

该变量只能在您声明它的范围内访问.如果您明确传递它,但是如果它保持有效则取决于变量的存储类型,可以在范围之外访问它.
例如:静态变量在整个程序生命周期内保持活动状态,同时,
从函数返回自动变量的地址将导致未定义的行为,因为该函数返回后变量不会保持有效.

好读:
What is the difference between a definition and a declaration?

How can I monitor the exact memory usage of my programs and its changes (i.e.: changes in memory usage by creating and destroying variables)?

我相信您会希望获得有关动态分配对象的信息,因为自动对象只能在其范围内存活足够长时间,它们将自动销毁,因此它们通常不会导致任何问题.

对于动态对象您可以使用内存分析工具(如valgrind with Massif)或replace new and delete operators for your class来收集诊断信息.

编辑:解决更新的问题.

In following code I know v scope is if block,but I want to know whether v is created/destroyed in the memory at the start/end of the if block or at the start/end of the function func?

当声明它的作用域开始并且声明它的语句被执行时,就会创建v.一旦达到范围,即销毁v.
这个概念用于形成C中最广泛使用的概念之一的基础,称为Resource Allocation is Initialization(RAII).每个C程序员绝对必须知道它.

通过这个小的修改过的code sample,演示和验证对象的创??建和销毁很简单:

#include<iostream>
class Myclass
{
    public:
        Myclass(){std::cout<<"nIn Myclass Constructor ";}
        ~Myclass(){std::cout<<"nIn Myclass Destructor";}
};

void func()
{
    std::cout<<"nBefore Scope Begins";
    if (true)
    {
        Myclass obj;//automatic storage class
    }
    std::cout<<"nAfter Scope Ends";
}

int main()
{
    std::cout<<"nBefore Calling func()";
    func();
    std::cout<<"nAfter Calling func()";
    return 0;
}

输出是:

Before Calling func() Before Scope Begins In Myclass Constructor In Myclass Destructor After Scope Ends After Calling func()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读