Could you please, to your understanding of the function exp in the way you have written it, explain what it does. Explain what each line of the function does.
Well, I read it somewhere that as soon as a function encounters a return statement it stops execution, so I think exp should never execute the i+=2, in fact it should never even come across it. And, moreover a(in exp) is the alias of i (in the main) so any change in a(in exp) should be reflected in i ( in the main) but a is never being changed in exp, it is just being assigned to i ( in exp) and i is getting incremented each time. So I think
for (int i=0; i<=a; i+=exp(i))
is equivalent to
for (int i=0; i<=a; i++)
Your exp() function is pointless - what's the goal of exp() here?
Dhanshree Arora wrote:
1 2
return i;
i+=2; // Ignored.
Once return is reached, any subsequent statements are ignored. You already know this, so why keep it there?
Dhanshree Arora wrote:
"should be reflected in i ( in the main) but a is never being changed in exp"
This is because i (in exp()) is a copy of i in main(). Since a is an alias, working with it is the exact same as working with the referent directly. So in essence, you're copying i in main().
Because of the way you increment i in your for loop.
the value of i used for that for loop will be 0 1 3 7 which obviously is 4 times, therefore, your code printed STRING 4 times.
trace it by substitute actual value to i starting with 0.
you are passing a reference to exp() , so the changes within that function will change the value of i in main.
trace it by substitute actual value to i starting with 0.
you are passing a reference to exp() , so the changes within that function will change the value of i in main.
I thought of that too, but am getting confused while I try to trace the entire process 'cause of the return statement. I am perceiving it this way, for i=0 in main, STRING is printed once. Then exp is called where i if referenced to a, and a assigns 0 to i in exp which increments once and returns the value.
1. Shouldn't the function STOP execution 'cause of this return?
2. If it does not and carries out i+=2, how does this affect the i in main? i (in exp) is not referenced to i(in main), and a(in exp) undergoes no change to change i (in main). Let's suppose it does, then how will you trace it? Can you please elaborate?
i += 2; is ignored because of the return above it. I think you get this part.
It make no effect to i in main.
if you changed it
1 2
i += 2; //Not ignored anymore
return i;
then the value of i in main() will be referenced to increased by 2 as well (by saying this, it means in addition to whatever changes made to i previously)
one thing is that you should give variables different names to avoid being confused of which is being used/talked about.