If I define a variable inside a control structure block, does it exist only when this control structure block is executed, and not in the entire execution of the closing function?
It depends on where you declare the define variable.
A variable is only available in the area where you declare it. It may be available outside the scope if you explicitly pass it, but if it remains valid, it will depend on the type of storage of the variable.
For example, static
variables are preserved throughout the entire program life cycle, and the return address of an automatic variable from a function will lead to Undefined Behavior, because the variable will not remain valid after the function returns.
Good Reading: What is the difference between a definition and a declaration?
How can I control the exact memory usage of my programs and its changes (i.e.: changes in memory usage by creating and deleting variables)?
I believe that you will want to get information about dynamically distributed objects, because automatic objects live long enough in their area, they will be automatically destroyed, so they usually do not cause any problems.
For dynamic objects, you can use memory profiling tools such as valgrind with Massif , or you could replace the new
and delete
statements for your class and collect diagnostic information.
EDIT: To refer to the updated Q.
In the following code, I know that region v
is an if
block, but I want to know if v
will be created / destroyed in memory at the beginning / end of the if block or at the beginning / end of the func
function?
v
is created when the region in which it is declared begins and the statement in which it is declared is executed. v
destroyed upon completion of the scope ie }
.
This concept is used to form the basis of one of the most widely used concepts in C ++, known as Resource Initialization (RAII) . Every C ++ programmer must be aware of this.
Itβs easier to show and verify the creation and destruction of objects using this small modified example.
#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; }
Conclusion:
Before calling func ()
Before You Start Scope | In Myclass Constructor
In Myclass Destructor
At the end of the transaction After calling the func () function