Could anybody explains to me why the result is 2, which x is using and why.
auto x = 0;
int f(int i){
auto x = 1;
{
static auto x = 0;
x += i;
}
return x;
}
int main() {
cout << f(1) + f(2) <<endl;// result 2
return 0;
}
The inner x shadows the outer one, but the mutations only apply to the inner most scope
int f(int i){
auto x = 1; // consider this "x1"
{
static auto x = 0; // this is "x2"
x += i; // mutates "x2" but not "x1"
}
return x; // return "x1" which is still 1
}
Therefore
f(1) + f(2) // 1 + 1 == 2
This is all about variable shadowing.
The innermost x in function f is shadowing the automatic x in that function. So that function is equivalent to
int f(int){
auto x = 1;
return x;
}
Note furthermore that the x in my abridged version shadows the one at global scope.
The function f is further abbreviated to
int f(int){
return 1;
}
and now the program output should be obvious.
In fact this function
int f(int i){
auto x = 1;
{
static auto x = 0;
x += i;
}
return x;
}
can be rewritten like
int f(int i){
auto x = 1;
return x;
}
because the static variable x declared in this block scope
{
static auto x = 0;
x += i;
}
is not used outside the block and does not influence on the returned value of the function. The only side effect of this code block is potential overflowing of the static signed integer variable x that has undefined behavior.
So the both function calls f(1) and f(2) returns 1 and as a result the expression f(1) + f(2) yields 2.
In the program there are declared three variables x. The first one in the global name space
auto x = 0;
The second one in the outer-most block of the function f that hides the declaration of the variable x in the global name space.
auto x = 1;
And the third one is declared in an inner block of the function f
{
static auto x = 0;
x += i;
}
that is not visible outside this inner block.
Related
I'm having a small issue in trying to figure out why a zero is printed out at the end of my while loop.
#include <iostream>
using namespace std;
int x;
int CountDown(int x);
int CountUp(int x);
int main()
{
int toCountUp = CountUp(x);
cout << x << endl;
}
int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}
My best response would be that it is in the condition of the while loop. Or a return status from the function/main being fulfilled, but I don't have a return on there, and I know a function doesn't require a return statement but in this while loop I want there to be a integer returned, do I need to make the function void so there will be no return? But what about the parameter x that I need for the while loop?
code output:
0
1
2
3
4
5
6
7
8
9
10
0 < ---- this is the number I do not want.
Thinking about it, it has to be a value returned at the end of the function, any ideas?
This outputs the values 0 through 10:
int toCountUp = CountUp(x);
Then, this outputs 0:
cout << x << endl;
The method does not change the value that is passed to it, it uses its own local copy of that variable.
—It's mainly because you are printing cout << x << endl; twice. Once in the int CountUp(int x) function itself, but again in the main function.
—It could've printed any given value of x at this point, but since you're setting x=0 outside of the While{} loop in the int CountUp(int x) function, it's printing 0 at the end after the function call is executed.
*int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}*
—Is there a reason why you are setting x=0 within the function? since you're passing x as a parameter in the function call, and adding 1 to it in the While{} loop until it's x<= 10? Asking because you're not returning x back to the main() function.
—In case you wanted to use the end value of x to countdown using CountDown(x), you may like to reset x=0 in the main() function after calling the block—
*int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}*
At last 0 is printed in main() function because x is declared global.
If you want latest x after loop got over to be printed in main() then you should reference variable and don't declare it globally.
int CountUp(int &); /* function prototype*/
Since passed variable(actual argument) and reference variable having the same memory So modification will affects in calling function.
int CountUp(int &x) { /* catch with reference variable so that modification affects in calling function also */
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}
First read Shadowing variables and What's the difference between passing by reference vs. passing by value?
The int x parameter of CountUp shadows the global variable int x so inside CountUp, the only x is the parameter.
int CountUp(int x)
int x defines x as passed by value, so it is a copy of the x used to call CountUp in main. This different x is counted up to 10 and then discarded.
the global int x has static storage duration and is default initialized to zero for you. Do not try this trick with a variable with Automatic duration because unless it has a constructor that does something useful, the contents are uninitialized and their value is undefined.
Sideshow issue:
A function that has a non-void return type MUST return a value on ALL paths. If it does not, you have Undefined Behaviour and the compiler can generate hopelessly invalid code that can get you even if the bad path is not taken. Don't smurf with Undefined Behaviour, as it might crash the program or do something hilariously wrong, but it might also look like it works until it suddenly doesn't at a really bad time.
Solutions:
void CountUp(int & x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}
Passes x by reference allowing global x and the local x to be one and the same and returns nothing.
Usage would be
CountUp(x);
Not so useful in the asker's case because it doesn't leave a toCountUp.
int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
return x;
}
Makes a copy if the provided x, operates on the copy, and then returns x. Usage would be
int toCountUp = CountUp(x);
And will set toCountUp to 10 higher than the global x.
The following while loop does not terminate. This is because the variable x is being re-declared inside the while loop. But I don't understand why in the second iteration onward, the statements x<10 and y=x considers the x defined in the outer scope and not the x defined in the block scope in the following statement.
Is this because once the first iteration ends, the x defined in the block scope is destroyed and the loop begins to execute fresh?
#include<iostream>
int main () {
int x = 0, y;
while(x <10 ){
y = x;
std::cout<<"y is :"<< y <<std::endl;
int x = y + 1;
std::cout<<"x is :"<< x <<std::endl;
}
std::cout<<"While loop is over"<<std::endl;
}
Every iteration the while loop evaluates the outer scope x and y is assigned the value of the outer scope x. After that another x is defined in the inner scope which is what the second std::cout uses, but the program makes no other use of the inner x
In the code below I replaced the inner x with z but otherwise the behavior is identical. The only difference is that there is not a second x within a more inner scope to hide the outer one:
#include<iostream>
int main () {
int x = 0, y;
while(x <10 ){
y = x;
std::cout<<"y is :"<< y <<std::endl;
int z = y + 1;
std::cout<<"z is :"<< z <<std::endl;
}
std::cout<<"While loop is over"<<std::endl;
}
Below I have an example that is intended to clear the confusion. In the inner scope x is not being "re-declared", a new x is being declared and it goes out of scope after the }:
#include<iostream>
int main () {
int x = 1;
{
int x = 2;
std::cout << x << '\n'; // 2
}
std::cout << x << '\n'; // 1
}
Yes, you understand it correctly. So every time when compare in while, it is using the outer x.
while (x < 10) {
y = x; //Here the x is the outer one. The inner one does not exist yet.
std::cout << "y is :" << y << std::endl;
int x = y + 1; // From here, x will refer to the inner one.
std::cout << "x is :" << x << std::endl;
// inner x is destroyed.
}
It is possible to store and wrap member functions with std::mem_fn.
In C you can use offsetof(...) on a member variable to crudely wrap a member variable (but only on a some types).
Is it possible to wrap a member variable in C++? What's the cleanest way?
ie
class X
{
...
M m;
...
};
mem_var<M> xm = &X::m;
int main()
{
X x = ...;
M i = ...;
xm(x) = i; // same as x.m = i
cout << xm(x); // same as cout << x.m
}
Yes, you can do it with... std::mem_fn.
struct B
{
int x;
int y;
};
int main()
{
auto m = std::mem_fn(&B::y);
B b {0, 0};
m(b) = 4;
printf("%d %d\n", b.x, b.y); // prints 0 4
printf("%d\n", m(b)); // prints 4
return 0;
}
Demo: http://ideone.com/40nI2
I'm trying to make a function that takes in either 1 or 3 parameters, and returns either 1 or 3 values (based on parameters passed).
If 1 parameter is passed then the function uses default values for the other 2 arguments.
If 3 parameters are passed then it uses those values.
bool foo( bool x, int &y = 0, int &z = 0) {
x = true; y = y + 1; z = z + 2;
return x;
}
Is this possible in C++ or am I confused with Java functions.
You can do it with two functions:
bool foo( bool x, int &y, int &z) {
x = true; // this isn't really what it does, is it?
y = y + 1; z = z + 2;
return x;
}
bool foo(bool x)
{
int a = 0, b = 0;
return foo(x,a,b);
}
Any function always returns only 1 value. Returning 2 or more values is not possible directly.
Indirectly, it happens when you pass parameters by reference. Since the two parameters &y and &z are passed by references, hence changes to them can be reflected back directly.
You can do this by passing by reference..
by doing so you are making a method that points to a memory location.
When that memory location is changed, then your value is changed.
Link
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr233.htm
You cannot do that this way. You can, however, overload that function with different number of parameters, and return, maybe, a std::vector or std::list with the results.
EDIT:
Being more sophisticated, you can use tuples for that:
typedef boost::tuple<bool,int,int> my_data_t;
my_data_t my_tuple(true, 1, 0);
then, you define your function like this:
bool foo( my_data_t & t)
{
t.get<0>() = true;
int& y = t.get<1>();
y = y+1;
int& z = t.get<2>();
z = z+2;
return t.get<0>();
}
and call it this way:
bool result = foo ( my_tuple );
then, out of the function, you'll see my_tuple.get<1>() (the corresponding to y) as 2 (1+1).
I am not sure what you are trying to do, but you can kind of return multiple values of different type using boost::tuple.
boost::tuple<bool, int, int> foo( bool x, int y = 0, int z = 0) {
x = true; y = y + 1; z = z + 2;
return boost::make_tuple(x, y, z);
}
int main() {
boost::tuple<bool, int, int> result = foo(x, 1, 2);
std::cout << boost::get<0>(result) << boost::get<1>(result) << boost::get<2>(result);
}
You could also use boost::optional, if you only want to return x, if only 1 parameter is passed.
Btw. tuple is available in C++11 too.
suppose I have this recursion:
void doSomething(double j)
{
double x;
double y;
x = j -1;
y = j -2 ;
doSomething(x+y);
x = j + 31;
y = j + 12 ;
}
I know that this recursion executes infinitely, but just ignore that
My question is with regards to variables x and y's scope in the recursion tree...will x and y's scope be valid only for the function in that specific stage in the recursion tree? or when I call doSomething() again, when the child doSomething() in the recursion tree redeclares x and y, will it reset the parents' x and y variables as well or is it creating an entirely new x and y variables that is valid for that stage in the recursion tree only?
will x and y's scope be valid only for the function in that specific stage in the recursion tree?
Yes.
when I call doSomething() again, and the child doSomething() in the recursion tree, redeclares x and y, will it reset the parents' x and y variables as well
No.
is it creating an entirely new x and y variables that is valid for that stage in the recursion tree only?
Yes.
Edit 1:
This example should be helpful.
#include <iostream>
void foo( int temp )
{
int num = temp;
if( temp == 0)
return;
foo(temp-1) ;
std::cout << &num << "\t" << num << "\n" ;
}
int main()
{
foo(5) ;
return 0;
}
Output:
0xbfa4e2d0 1
0xbfa4e300 2
0xbfa4e330 3
0xbfa4e360 4
0xbfa4e390 5
Notice the address of num being different and each call has it's own value of num.
Ideone
Every call gets its own copy of the variables. Assigning to the copy in one function call has no effect on the versions in any other function call. That's why the recursion has to communicate between "stages" by passing arguments and returning a value.
yes, x and y are stack variables, and thus are independent between each call. A fresh, stack-based x and y will be created for each call to doSomething.
If you wanted them to be the same variable in each call, you should declare them static
Every time a function is invoked, there are new local variables x and y created, that are unrelated to any other invocation of the function. This is what makes local variables different from global variables.
You are passing x + y by value into the function doSomething(). This means that on the function stack doSomething() will have access to one local variable j with its value set from the function below it on the stack to whatever x + y evaluates to (i.e the function that called them). Since this variable is completely separate from that in the parent function, modifying its value will have no affect on variables below it on the stack.
If, however, you want j to be the exact same variable as in the parent function then you can do something like:
void doSomething( double& j )
{
double x = j - 1;
double y = j - 2;
double willChange = x + y;
doSomething( willChange );
x = j + 31;
y = j + 12 ;
}
Notice the & after the double, this tells the compiler that the function accepts the value of a double by its address, which is called appropriately enough passing by address. Here in the child of every doSomething() j is an alias for the variable willChange in the function below it on the stack.
If you want to modify x and y specifically then maybe do something like
void doSomething( double& x, double& y )
{
double j = x + y
double x = j - 1;
double y = j - 2;
doSomething( x, y );
x = j + 31;
y = j + 12 ;
}