Lambda function is giving unexpected output - c++

I was going through lambda functions on https://shaharmike.com/cpp/lambdas-and-functions/ and found below code.
int i = 0;
auto x = [i]() mutable { cout << ++i << endl; };
x();
cout << i << endl;
auto y = x;
x();
y();
Output:
1
0
2
2
Unable to understand why last 2 statements are getting printed as 2 and 2. Even though 'i' is mutable, it will not effect i value outside lamda function. so, x() and y() should print 1 and 1. Can any one please explain why it is printing 2 and 2.

x has a copy of i. I will call it x.i.
x(); -- prints ++x.i, aka 1
cout << i; -- prints i, aka 0
auto y = x; -- copies x into y. x.i is 1, y.i is also 1.
x(); -- prints ++x.i, aka 2
y(); -- prints ++y.i, aka 2

The value of i is saved as a field of the functor generated by the lambda function, so when you copy it, the field is copied as well with the value 1. Then calling the functor increments each object's i field and displays that value, so you get 2 and 2.

Related

is it possible to explain why this returns 21

Hello this isn't an assignment or anything but can you explain why this returns 2 1.
#include <string>
using namespace std;
void fun(int);
int main()
{
int a = 0;
fun(a);
return 0;
}
void fun(int n)
{
if (n < 2)
{
fun(++n);
cout << n<<" ";
}
}
Flow of fun() :
You are passing a which is initialized to 0 as the parameter to the fun(). So, You call fun(0) from main().
In the call fun(0) the condition n<2 is true since at the start, it is 0. So the function fun(0) will
call fun(++n),that is fun(1) and push the current function call on the stack. Notice, the value of n in the function call which is pushed has increased to 1.
Again, n<2 evaluates to true since now the value of n is 1. The
function will call fun(++n) again, that is fun(2) and push the current function call to stack once again.Notice, the value of n in the function call which is pushed has increased to 2.
Now, the value of n is 2 and hence n<2 evaluates to false. So,
this time it will not do anything and just terminate
Now, the last function call will get popped from stack and cout will get executed. So, the control returns to the function at the top of the stack, which in our case is fun(1). But, here we had increased our n by doing ++n (Check point : 3). So the value printed will be 2. This function call now gets terminated.
Now, at the top of stack is the function call that we pushed at first, that is fun(0) but our value of n was increased by ++n (Check point : 2). So now the value of n which is 1 will be printed.
Hope you understand the above explanation and this solves your doubt !
You can think about recursion as nesting the functions inside of each other.
You pass n = 0.
fun(n=0)
{
if (0 < 2)
{
// ++n alters n to be equal to n+1 for our current scope.
fun(++n); // n = 1 now, fun gets called with n = 1
{
fun(n=1)
{
if (1 < 2)
{
fun(++n); // n = 2 now, fun gets called with n = 2
{
fun(2)
{
if(2 < 2) // returns false
}
} // we exit this scope without doing anything futher
cout << n << " "; // n = 2 in this scope, here we print the 2
}
}
} // now we exit this scope
cout << n<<" "; // n = 1 in this scope, here we print the 1
}
}
Please let me know how I can clarify this further.
This code does not return anything, except for the main function that returns 0 exit code. The function fun just prints.
It prints 2 1, because it computes this:
void fun0()
{
fun1();
cout << 1 <<" ";
}
void fun1()
{
cout << 2 <<" ";
}
Therefore it first prints 2 and then prints 1 after the code returns from fun1.
Every time you make a recursive call a new instance of n will be created. The program will only reach the first cout after two recursive calls, so n will be 2 at that point. I don't want to explain how everything works in detail, I genuinely think that if you write some more printf's you will be able to figure out what the program is doing by yourself. If you figure this out by yourself with my simple hints you'll know how recursion works pretty well.
fun() is a non tail recursion call and base condition is n<2 then
fun will call twice fun(0) &fun(1). As recursion activation record maintain on stack then while reaching at base condition it will print
2 1
Cout "2"
Cout "1"
I will recommend please go through recursion concept thoroughly.
Firstly function will not return anything until you add a return statement in the function, In your case you are not returning the value, you wrote a statement to print/display the current value of 'n' initially you set a=0 and calling a function "fun(a)" and passing the value of "a" So, in the "fun" function you added a condition which says the value of "n" should be smaller than "2", then you are using the recursive method(a function that calls itself) and pre incrementing "++n" the value of "n" and passing it in the fun function.
n = 0
fun(n)
fun(0){
if (n < 2) *first call true
{
fun(++n); *n = 1 before going to next condition it is calling itself*
cout << 1<<" ";
}
}
fun(1){
if (n < 2) *true*
{
fun(++n); *n = 2 again before going to next condition it is calling itself*
cout << 2<<" ";
}
}
fun(2){
if (n < 2) *flase*
{
fun(++n);
cout << n<<" ";
}
}
So, it will print 2 and then 1.
flow of Recursive function
I hope you get your answer.

how does global variable increment work in c++

#include <iostream>
int counter = 0;
int f(){
return counter++;
}
int main(){
std::cout << f(); //output = 0
std::cout << f()+f(); // output = 1;
return 0;
}
This might be a silly question but why isn't f() equal to 1 instead of 0 in the first case?
I thought counter++ was the same as counter = counter + 1?
No. counter++ is closer to (counter = counter + 1) - 1
Its because of the difference between postfix and prefix notation. In postfix notation which is what you have currently it saves a copy of the variable and then increments the variable for any calls below the current call however at the current call it will appear to stay the same.
This is why when we have std::cout << f(); //output = 0 it outputs 0 because counter will only increment after this line. If you change f to:
int f() { return ++counter; }
You will see the result you expected.
first, Are you sure f() + f() results in 1. I think it should be 3.
Regarding your main question:
post increment works on a copy of the original value. so your function in f() is acting as:
int f()
{
int temp = counter;
counter = counter + 1;
return temp;
}
or as cleverly noted by #kmkaplan:
int f()
{
return (counter = counter + 1 ) - 1;
}
it is similar to the semantic of:
int f = 0;
cout << f++; // f original value is first displayed.
cout << ++f; // f is incremented then displayed.
In general, I prefer to use ++n over n++ unless the program logic requires the opposite.

Evaluation order in initialization

In the following program:
#include <iostream>
struct I {
int i;
I(){i=2;}
I(int _i){i=_i;}
};
int a[3] = {a[2] = 1};
int aa[3][3] = {aa[2][2] = 1};
I A[3] = {A[2].i = 1};
I AA[3][3] = {AA[2][2].i = 1};
int main(int argc, char **argv) {
for (int b : a) std::cout << b << ' ';
std::cout << '\n';
for (auto &bb : aa) for (auto &b : bb) std::cout << b << ' ';
std::cout << '\n';
for (auto &B : A) std::cout << B.i << ' ';
std::cout << '\n';
for (auto &BB : AA) for (auto &B : BB) std::cout << B.i << ' ';
std::cout << '\n';
return 0;
}
The output is
1 0 0
1 0 0 0 0 0 0 0 1
1 2 2
1 2 2 2 2 2 2 2 2
from http://ideone.com/1ueWdK with clang3.7
but the result is :
0 0 1
1 0 0 0 0 0 0 0 1
1 2 2
1 2 2 2 2 2 2 2 2
on http://rextester.com/l/cpp_online_compiler_clang also with clang 3.7.
On my own ubuntu, gcc 6.2 givs an internal compiler error on the construct int aa[3][3] = {aa[2][2] = 1}.
I'm assuming this is undefined behavior, but cannot find a definitive statement in the standard.
The question is:
Whether the evaluation order of the side effects on the assignment in the initializer list (e.g. a[2] = 1) and initialization of the actual element of the array (e.g. a[2]) defined in the standard?
It is explicitly stated as defined or undefined? Or does it become undefined just because it is not explicitly defined?
Or does the construct has defined or undefined behavior due to other reason aside from the evaluation order?
Let's start with the simplest case:
I A[3] = {A[2].i = 1};
I AA[3][3] = {AA[2][2].i = 1};
Both of these are UB, due to a violation of [basic.life]. You are accessing the value of an object before its lifetime has begun. I does not have a trivial default constructor, and therefore cannot be vacuously initialized. Therefore, the object's lifetime only begins once a constructor has completed. The elements of the A array have not yet been constructed when you are accessing elements of that array.
Therefore, you are invoking UB by accessing a not-yet-constructed object.
Now, the other two cases are more complex:
int a[3] = {a[2] = 1};
int aa[3][3] = {aa[2][2] = 1};
See, int permits "vacuous initialization", as defined by [basic.life]/1. Storage for a and aa has been acquired. Therefore, int a[3] is a valid array of int objects, even though aggregate initialization has not yet begun. So accessing the object and even setting its state is not UB.
The order of operations here is fixed. Even pre-C++17, the initialization of the elements of the initializer list is sequenced before the aggregate initialization is invoked, as stated in [dcl.init.list]/4. Elements in the aggregate which are not listed in the initialization list here will be filled in as if by typename{} constructs. int{} means to value-initialize an int, which results in 0.
So even though you set a[2] and aa[2][2], they should immediately be overwritten via aggregate initialization.
Therefore, all of these compilers are wrong. The answer should be:
1 0 0
1 0 0 0 0 0 0 0 0
Now granted, this is all very stupid and you shouldn't do it. But from a pure language perspective, this is well-defined behavior.

Big Theta (Θ) runtime of recursive functions

I'm having trouble trying to understand the runtime. Any help would be much appreciated!
int foo(int x) {
if (x <= 0) return x;
cout << x;
return foo (x-1);
}
void bar(int n) {
if (n <= 0) return;
cout << foo (n) << endl;
bar (n-1);
cout << n;
}
int main() {
int n;
cin >> n;
bar(n);
return 0;
}
Foo is printing the number you passes and it will do x-- until is 0, if you pass 5 it will print 543210, so you can called it decrement n by 1 and print the result
Bar is doing the same without printing, only decrementing and calling foo
It is a 3 recursion level, try to use a small number and follow the flow, like 4
-Bar gets 4, the case base it is 0, 4 is greater than 0 so it will continue, it will call foo(4) (remenber that foo is a recursive call that will print 4 to 0 => 43210, decrementing the number by 1 each time)
-And bar gets called again, this time with n-1 = 4 -1 = 3, with the value 3, it will call foo(3) and the same
When you meet the case base in bar, n == 0 you will stop calling anothers functions and this function will get the value returned, you can print on screnn but it doesnt mean that the function ends, it was waiting for the other values to return, when it returns it prints the n that called it, so it will be 1234, that is it that the values 1, 2, 3 and 4 are the values that enter bars one at a time and prints the value of the result of foo (for 4,3,2,1) because it is what you get
int foo(int x) { //Decrementing by one and printing the value
// If x reaches 0 exit (you need an exit in a recursion)
if (x <= 0) return x;
// Print the value x (the first time x will be the n, the second n-1)
cout << x;
// Call the same function in we are but with x-1 value
return foo (x-1);
}
// It will produce foo(4)=>foo(3)=>foo(2)=>foo(1) and foo(0)
// foo(0) will break the recursion and finish here (only prints)
// It is where main calls and enters n is the value you type
void bar(int n) {
// Case base to break recursion when it reaches 0
if (n <= 0) return;
// Here is the code that prints the line that foo will make
cout << foo (n) << endl;
// Here you will call the same function but with n-1, like foo does
bar (n-1);
// When all the recursion above is over you will get here
// In the stack you will have done n calls into here with n-x
// So every one will print the value of n that in the paremeter
// when the call was make
cout << n;
}

Difference between pre and post decrement in recursive function argument

I have following sample code where i used pre-decrement
void function(int c)
{
if(c == 0)
{
return;
}
else
{
cout << "DP" << c << endl;
function(--c);
cout << c << endl;
return;
}
}
This function give output for input 4 as :
DP3
DP2
DP1
DP0
0
1
2
3
But when i use post decrement
void function(int c)
{
if(c == 0)
{
return;
}
else
{
cout << "DP" << c << endl;
function(c--);
cout << c << endl;
return;
}
}
Output goes in infinite loop with DP4
Can you explain me in detail why this happens ?
This happens because function(c--) will be called with the same value of c and when it finishes c will be decremented. But as it is recursively called, hence it will be called with same value with no chance of return and eventually you will hit stack overflow error.
Assume this, int x = 1, y = 0; Now y = x++ will result y == 1 and x == 2. But if you do y = ++x , then bot x and y will be 2.
Because --c will return c-1,however c-- return c.So when you use function(c--) is equal to function(c);c = c-1;.c will never be 0.So the function won't stop.
To know the difference between --x and x-- you can try the following code:
int x = 5,y=5;
cout<<x--<<endl;
cout<<--y<<endl;
cout<<x<<" "<<y<<endl;
In case of post decrement value will be passed before decrement , always same value will be passed to function , it never come out .
function(c--), first it call function(c) later decrement c-- will happen .