C++ Pointers and reference and functions - c++

I dont understand how this code works can you please explain it to me.
#include <iostream>
using namespace std;
int fun (int &x, int &y) {
if (y<=0)
return x;
x=x+2;
cout<<x<<y<<endl;
return x*y;
}
int main () {
int x=5, y=-1;
cout <<fun(x,y)<<endl;
fun(y,x);
fun(x,y);
fun(y,x);
cout <<fun(x,y)<<endl;
return 0;
}
the correct answers are
5
15
71
37
93
27

The first function call cout << fun(x,y) << endl; passes x as 5 and y as -1. Because y is less than 0 the function simply returns x to cout, so it prints 5.
The next function call fun(y,x) which still passes -1 and 5, however this time the values are passed in reverse so within the function x is -1 and y is 5. Because y is 5 the if statement is false and x is assigned -1 + 2, or 1. Then x as 1 and y as 5 are printed and the multiplication of the two is returned, however nothing is done with the multiplied value.
The third function call passes x and y, but in the previous function call x (as y) was changed to 1. Because the value was passed in as a reference of y, it is now 1. So, x is assinged 5 + 2 and x and y are printed as 71.
The fourth function call passes x and y again in reverse. So, recall that x was changed to 7 and y is 1. But the values are in reverse so in our function x is 1 and y is 7. So again x is assigned the value of 1 + 2 and these are printed as 3 and 7.
Finally, the last function call passes x and y, but remember that x (as y) was changed to 3. So now x is 7 and y is 3. Once more x is assigned 7 + 2, and x and y are printed as 93. Since the function was called from a cout statement the multiplication of 9 and 3 is also printed as 27.

Related

Function call in for loop declaration [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Could anybody explain me how this code is actually working?
when I run it, It gives me 52 as an output.
#include <iostream>
using namespace std;
int Fun(void){
static int x=7;
return x--;
}
int main(void)
{
for(Fun();Fun();Fun())
cout<<Fun();
return 0;
}
Every "regular" for loop has 3 parts :
initialization
condition
iteration
On entering x is 7, initialization will return 7, decrement and go on with the condition where x is now 6. Upon condition it will return 6 (which is truthy), decrement and go on with the body where x is now 5. Upon printing, it will return 5, decrement and go on with the iteration where x is now 4.
Upon iteration it will return 4, decrement and go on with the condition where x is now 3. Upon condition it will return 3 (which is truthy), decrement and go on with the body where x is now 2. Upon printing it will return 2, decrement and go on with iteration where x is now 1.
Upon iteration it will return 1, decrement and go on with the condition where x is now 0. Upon condition it will return 0, which is falsy, and thus break out of the loop.
One of the important things to understand is that x is static and thus is part of the "state" of the function. It is initialized on first call and reused on each call.
probably you better understand with this code, since you are doing cout << Fun(); you see only the value at that time, you can see the return value at each phase with below code.
first initialization of for you get 7,
second condition check you get 6, since its non zero enters into loop.
inside loop call Fun which prints 5
then go to update part of for loop where we receive is 4
after that go to condition check it gives 3, since its non zero enter the loop
inside loop this time it will print 2
then go to update part of for which return 1
then go to condition check which gets 0, loop terminates.
#include <iostream>
using namespace std;
int Fun()
{
static int x=7;
return x--;
}
int main( )
{
int x, y, z = 0;
for( x = Fun(); y = Fun();z = Fun())
cout<<"x = " <<x<<" y = "<<y<<" z = "<< z<<" and Fun ="<<Fun()<<endl;
return 0;
}
After each call of the function Fun the static variable x is decremented. The function returns the value of the variable x before decrementing.
So in this for loop
for(Fun();Fun();Fun())
cout<<Fun();
Before the body of the loop gets the control the function Fun was called two times
for(Fun();Fun();Fun())
1 2
So after these calls the value of the variable x is equal to 5. This value is outputted in the statement
cout<<Fun();
and after the call of the function used in this statement the value of x becomes equal to 4.
Then again the function Fun was called two times
for(Fun();Fun();Fun())
2 1
So the value of the x becomes equal to 2. This value is outputted in the statement
cout<<Fun();
And after the call of the function in this statement the value of x is equal to 1. Then in the first call of Fun
for(Fun();Fun();Fun())
2 1
the value of x becomes equal to 0. This value is returned by the second call of the function. So the condition evaluates to boolean false.
Thus the loop outputted two numbers 5 and 2. The result value of the static variable x is -1. (0 was returned in the last call of Fun and after that the variable x was decremented)
To understand, you can "unroll" the loop:
int Fun()
{
static int x = 7;
return x--;
}
int main()
{
Fun(); // x is 6
if (!Fun()) return 0; // x is 5
std::cout << Fun(); // prints 5, x is 4
Fun(); // x is 3
if (!Fun()) return 0; // x is 2
std::cout << Fun(); // prints 2, x is 1
Fun(); // x is 0
if (!Fun()) return 0; // end
}
Note that Fun() returns a value which equals x+1.

Understanding the operator "less" or "greater" in assigning value with C++

I used greater than and less than signs and it gives ouput! How it is working ?
int x = 2;
x >= 3;
cout << x; // output is 2
And also the output is different like this
int x = 2;
x = x > 3;
cout << x; // output is zero !! HOW ??
The expression
x >= 3
is a pure comparison. It tests, whether the value of variable x is greater than, or equals 3. The result is 0 or 1 – for x equal 2 it is zero, false.
Terminating the expression with a semicolon creates a statement. That statement performs a comparison and ...nothing else. The result of comparison is discarded, and the variable x remains unchanged. Hence the observed resulting value 2.
In x = x > 3; the subexpression x > 3 is a comparison. Its result is 1 if the comparison succeedes, 0 otherwise.
Since you initialized x to 2, the result of the comparison is false, i.e. zero.
As a result
x = x > 3;
equivalent to
x = (x > 3);
resolves to
x = 0;
hence the output you observed.
If you use
int x = 2;
x >= 3;
cout << x;
the output is 2 because the result of the x >= 3 operation is discarded (not used) and x remains by the same value as it were initialized. x was not assigned by any value after its initialization.
If you use
int x = 2;
x = x > 3;
cout << x; `
x is checked whether it is greater than 3 or not with x > 3. If it is, the value of the expression x > 3 turns 1, if not it turns 0. Comparison operations are boolean expressions.
This boolean value is assigned back to x after the evaluation of x > 3.
Since x is not greater than 3, the expression x > 3 gains the value 0 and this value is assigned back to x and finally what is printed.

Order of Evaluation for passing function arguments - Order of operations for F1( int F2( int& x ), int x )

Okay so I was writing some code earlier. This was the line specifically:
EnterNode( FindNode( terrain_X, terrain_Y, travel_dir ), travel_dir );
I noticed after testing my program something weird was happening. The value being received by the outer function was not the value I was reading when I inspected the stack.
I made an example program:
https://ideone.com/wNjJrE
#include <iostream>
int modifyRef(int& A)
{
A = 0;
std::cout << "\nint& A = 0";
return A;
}
void TakeValues(int X, int Y)
{
std::cout << "\nX = " << X;
std::cout << "\nY = " << Y;
}
int main()
{
int Q = 9;
TakeValues(modifyRef(Q), Q);
std::cout << std::endl;
system("pause");
return 0;
}
This is the output I receive:
int& A = 0
X = 0
Y = 9
I would expect Y to also be 0. How is the order of operations defined for parameter binding to function calls?
(My apologies if I am not using the correct terminology.)
The evaluation order of function arguments is unspecified. When you write:
TakeValues(modifyRef(Q), Q);
you are relying upon the fact that modifyRef(Q) to be evaluated before Q. But the evaluation order of function arguments is unspecified - it is not necessarily the case that modifyRef(Q) will be sequenced before Q nor vice versa.
In this case, Q (the second argument) gets evaluated first. So we read 9, and initialize the parameter Y with it. Then we evaluate modifyRef(Q), which zeros out Q and returns it, which leads to initializing X with 0.
Try changing the signature of your functions:
int ModifyRef( int& A );
void TakeValues( int X, int Y );
to the following...
int& ModifyRef( int& A );
void TakeValues( int& X, int& Y );
and see what your output will be in main when you call this line of code:
int q = 9;
TakeValues( ModifyRef(q), q );
then reverse the order of the parameters as such
TakeValues( q, ModifyRef(q) );
and compare the results.
When I did this on my machine Win 7 64bit with VS2015 Community on an Intel Core2 Quad Extreme the results I was given for both situations when using references were the same and the output I am getting is:
I changed the value of A in ModifyRef() from 0 to 7 for testing purposes.
int& A = 7
X = 7
Y = 7
for both situations where either the inner function is the first parameter and the stand alone variable is the second or the inner function is the second parameter with the stand alone variable as the first.
Since I am receiving the same results it appears to me that do to how the compiler creates and handles the stack pointer the ModifyRef() appears to be evaluated first and once that function is finished since q is now being referenced instead of being a stack copy it is being overwritten by whatever value it is being set to within the ModifyRef function.
I also modified your ModifyRef() function slightly so that I can see what its passed in parameter is instead of having a number hard coded into its print out statement.
int& ModifyRef( int& A ) {
A = 7; // Changed Value From 0 To 7 For Testing Purposes
std::cout << "n\int& A = " << A;
return A;
}
However this effect may only apply when using only references.
When I revert back to your original function signatures and I call it in this order:
q = 9;
TakeValues( ModifyRef( q ), q );
As is your original code was presented the output I am getting is:
int& A = 7
X = 7
Y = 9
However when I reverse the parameters to:
q = 9;
TakeValues( q, ModifyRef( q ) );
My output is:
int& A = 7
X = 7
Y = 7
So what I am seeing in these two situations is slightly different.
In the first order of parameters, Y or the second parameter is being set to 9 as q is initialized to 9 and Y within TakeValues() is printing out a stack copy with a value of 9. Then X is being valuated by ModifyRef() where q has a value of 9 but then it is being modified since it is a reference so when TakeValues() sets X from q, q was already changed from 9 to 7 so X is now being set to 7.
In the second order of parameters it appears that ModifyRef() is being called first and changes q from 9 to 7 so TakeValues() is setting Y to 7 and since this function is using a reference q was also changed from 9 to 7, so when the first parameter is taking q to set X q was already changed from 9 to 7.
I do not know if this is compiler dependent but at least on my machine it appears that the call stack for the parameters is happening from farthest right to left. This also makes sense when you think about it due to when functions have default values.
Example:
class foo {
void bar( int a, int b, int c = 3 ) {
std::cout << a << ", " << b << ", " << c << std::endl;
}
};
All default values in a function declaration must be to the far right for you can not have:
class foo {
void bar( int a = 1, int b, int c ) { ... } // Compile Error
};
I hope this helps to clarify what is going on within your code when you begin to call a function within a function as a parameter either if you are using passing by value(stack copy) or by reference.

comma operators in c++

int main() {
int x = 6;
x = x+2, ++x, x-4, ++x, x+5;
std::cout << x;
}
// Output: 10
int main() {
int x = 6;
x = (x+2, ++x, x-4, ++x, x+5);
std::cout << x;
}
// Output: 13
Please explain.
Because , has lower precedence than =. In fact, , has the lowest precedence of all operators.
First case:
x=x+2,++x,x-4,++x,x+5;
This is equivalent to
(x=x+2),(++x),(x-4),(++x),(x+5);
So, x becomes 6+2 = 8, then it is incremented and becomes 9. The next expression is a no-op, that is x-4 value is calculated and discarded, then increment again, now x is 10, and finally, another no-op. x is 10.
Second case:
x=(x+2,++x,x-4,++x,x+5);
This is equivalent to
x=((x+2),(++x),(x-4),(++x),(x+5));
x+2 is calculated, then x is incremented and becomes 7, then x - 4 is calculated, then x is incremented again and becomes 8, and finally x+5 is calculated which is 13. This operand, being the rightmost one, is the taken as the result of the whole comma expression. This value is assigned to x. x is 13.
Hope it's clear.
And, as one of the comments suggests - NEVER WRITE CODE LIKE THIS

Can anyone help me find what the output is?? this is in C++

Can anyone help me find what the output is?? this is in C++... homwork
A variable x globally defined in your program is assigned the integer value 3. A variable x defined in a function named f_name is assigned the integer value 5. Answer the following after looking at the code that follows.
1 #include <iostream>
2 using namespace std;
3 int f_name(int y);
4
5 int x = 3;
6
7 int main()
8 {
9 cout << x;
10 cout << f_name(x);
11 return 0;
12 }
13
14 int f_name(int y)
15 {
16 int x = 5;
17 return (x + y);
18 }
What is the output of line 9? _________ line 10? _______________
3 and 8. No?
In line 9 cout << x; prints the value of the global x i.e 3.
In line 17
return (x + y ); // outputs 8
x refers to local x whereas the value of y is equal to global x's value since it is passed as an argument to the function.
line 9 = 3
line 10 = 8 are the outputs.
At line 9, just printing the value of global variable x.
At line 10, just passing the value of x to f_name(iny y). Which means value of y at this function scope is 3. Adding this to local variable x gives 8 which the function is returning.
I think, you are having trouble in understanding the scope of variables. To understand that, keeping this program in point of view, there are two kind of variables -
Local Variables
Global Variables
Local variables are variables that has local scope and are accessible only in the functions they are declared.
Global variables are variables whose life span starts at the begin of the program and ends only after program termination. Global variables at file scope are accessible any where with in the translation unit.
int main()
{
cout << x; // x here is the global variable. Because, in main, there is no variable
// called x declared. So it prints 3
cout << f_name(x); // Here you are passing the value of global variable x, which is 3
return 0;
}
int f_name(int y) // The passed value ( i.e., 3 ) is copied to y.
{
int x = 5;
return (x + y); // Here you are not accessing global variable x. Because, there
// is a local variable declared called x and initialize with value 5
// Now (5+3) = 8, which is returned.
}