Why is the following code prints "xxY"? Shouldn't local variables live in the scope of whole function? Can I use such behavior or this will be changed in future C++ standard?
I thought that according to C++ Standard 3.3.2 "A name declared in a block is local to that block. Its potential scope begins at its point of declaration and ends at the end of its declarative region."
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass( int ) { cout << "x" << endl; };
~MyClass() { cout << "x" << endl; };
};
int main(int argc,char* argv[])
{
MyClass (12345);
// changing it to the following will change the behavior
//MyClass m(12345);
cout << "Y" << endl;
return 0;
}
Based on the responses I can assume that MyClass(12345);
is the expression (and scope). That is make sense. So I expect that the following code will print "xYx" always:
MyClass (12345), cout << "Y" << endl;
And it is allowed to make such replacement:
// this much strings with explicit scope
{
boost::scoped_lock lock(my_mutex);
int x = some_func(); // should be protected in multi-threaded program
}
// mutex released here
//
// I can replace with the following one string:
int x = boost::scoped_lock (my_mutex), some_func(); // still multi-thread safe
// mutex released here
The scope of a variable is the region of a program in which the variable is visible, i.e., in which it is accessible by its name and can be used. In Java, the scope of a local variable is the body of the method in which it is declared.
Example 1: Local Scope Variable In the above program, variable a is a global variable and variable b is a local variable. The variable b can be accessed only inside the function greet . Hence, when we try to access variable b outside of the function, an error occurs.
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.
Declaration of Local Variable: In this case it is executed in the same manner as if it were part of a local variable declaration statement. For example: for(int i=0;i<=5;i++){……} In above example int i=0 is a local variable declaration. Its scope is only limited to the for loop.
The object created in your
MyClass(12345);
is a temporary object which is only alive in that expression;
MyClass m(12345);
is an object which is alive for the entire block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With