How to use values created inside a loop function? - c++

I would like to know which one would be the best way of using values created inside a loop, outside of that loop. I have for example the function:
void Loop(int a)
{
// recursion loop execution
for ( int i = 0; i < 10; i++ )
{
int new_a = a + i;
}
}
I would like to use that "new_a" as it is being "looped" in another function which is plotting a graph and only needs the "yAxe" value. Like that:
int main ()
{
int a = 5;
plot (x,Loop(int a);
}
I know I could create an array with the values of the loop but I wouldn't like to store them and for big plottings would be too much memory.

Any local variable will be destroyed when the scope of them be finished. For example, in your code new_a will be destroyed when the for loop is finished, and the a is destroyed when the function be finished. I mean if you care about memory, don't be worry.

If I understand you correctly, you want to call Loop multiple times (like e.g. Loop(a)) and each call you should get the next "iteration" of the loop?
That would have been easy if C++ had continuations which it doesn't. Instead it can be emulated by using classes and objects and operator overloading.
For example:
class LoopClass
{
public:
LoopClass(int initial_value = 0)
: current_value{initial_value}
{
}
int operator()(int a)
{
return a + current_value++;
}
private:
int current_value;
};
It can be used as such:
LoopClass Loop; // The value initialized with zero
int a = 5;
std::cout << "First call : " << Loop(a) << '\n';
std::cout << "Second call: " << Loop(a) << '\n';
The above code, if put into a program, should print
First call : 5
Second call: 6

Related

Recursion in the main function

I tried recursion in the main function, but why 'i' variable is not getting updated, it only gets updated till i=1 and then remains constant.
Below is the code:-
int main(int i = 0)
{
std::cout << "i value" << i << std::endl;
if (i == 3)
return 0;
std::cout << "hello" << std::endl;
main(i++);
}
See for example cppreference/main_function:
The main function has several special properties:
It cannot be used anywhere in the program
a) in particular, it cannot be called recursively
b) its address cannot be taken
[...]
You cannot call main recursively. Also your signature is not correct. Correct signatures are:
int main () { body } (1)
int main (int argc, char *argv[]) { body } (2)
/* another implementation-defined form, with int as return type */ (3)
For (3) you need to check your implementation, I am not aware of one that allows int main(int) (though I didn't bother to check).
Last but not least, foo(i++); will increment i and then call foo with the original value of i. You probably want foo(++i); or rather foo(i + 1);.
TL;DR
int my_main(int i=0) {
// put code here
my_main(i + 1);
}
int main() {
my_main();
}

mergesort not working in c++

Is there anything wrong with the usage of the "return" values of the three fuction? The values printed out are garbage values with seemingly random numbers as outputs.I would also like to add that i havent made it recursive because i wanted to check whether this would work or not.
Most all of the mergesort implementation I've seen hardly contain any return values, is that something im doing wrong. If you were to go about a similar type of implementation, how would you do it?
#include <iostream>
using namespace std;
int* goleft(int array[], int size)
{
int halved=size/2;
int left[halved];
for(int i=0;i<halved;i++)
{
left[i]=array[i];
}
return left;
}
int* goright(int array[],int size)
{
int halved=size/2;
int right[size-halved];
for(int i=halved,j=0;i<size;i++,j++)
{
right[j]=array[i];
}
return right;
}
int* mergesort(int array[],int size)
{
int *l,*r;
l=goleft(array,size);
r=goright(array,size);
int merger[size];
int halved = size/2;
int i;
for(i=0;i<halved;i++)
cout<<l[i]<<endl;
for(i=0;i<halved;i++)
cout<<r[i]<<endl;
int x=0,y=0,k=0;
while(x+y!=size)
{
if(l[x]<r[y])
{
merger[k]=l[x];
x++;k++;
}
else if(l[x]>=r[y])
{
merger[k]=r[y];
y++;k++;
}
}
return merger;
}
int main()
{
int size;
cin>>size;
int array[size];
for(int i=0;i<size;i++)
cin>>array[i];
int *merged=mergesort(array,size);
cout<<"sorted array"<<endl;
for(int i=0;i<size;i++)
cout<<merged[i]<<endl;
return 0;
}
And when we create variables of same name during loops and recursions, are new variable created for every loop iteration or recursion? or do they overwrite the value for the previous variable. for e.g when we write
while(true)
{
int i=0;
}
would a new variable be made at every iteration
and
genericFunction()
{
int i = SomeRandomValue
genericFunction();
}
similarly would a new variable be made at each recursion?
As you thought, the error is in "scopes". To answer to your questions :
while(true)
{
int i=0;
}
The process is :
//iteration N start
create scope
allocate memory for an int variable named 'i' in the current scope
//statements done
delete current scope //deallocate the variables in the current scope
//iteration N end
//iteration N+1 start
/*...*/
So in each iteration it is a different variable. You can test it with this code :
while (true) {
int i;
std::cout << &i << std::endl; //displays the memory location of i
system("PAUSE"); //waiting user input between each iteration
}
In the example with genericfunction, the process is :
//N call to genericFunction
create scope //scope N
//N+1 call to generic Function
create scope //scope N+1
/* statements */
delete current scope //scope N+1
// exit of call N+1
delete current scope //scope N
//exit of call N
You can test it with this complete code :
#include <iostream>
void genericFunction(int a)
{
int i = 0;
std::cout << "scope " << a << " : " << &i << std::endl;
if (a < 9) { //to prevent infinite call
genericFunction(a + 1);
}
std::cout << "scope " << a << " : " << &i << std::endl;
}
int main() {
genericFunction(0);
system("PAUSE");
return 0;
}
A generic rule is : when you have {, you create a new scope and select it as current scope, when you have }, you delete the current scope and select the previous scope. Some scopes permits access to previous scopes (for example a WHILE LOOP : in the code int a; while(true) {a++;}, it modifies the value of a in the previous scope), but when a function scope is created you have no access to previous scopes.
Now for your specific issue with mergedsort, it is the declaration of your variable merger inside the function mergesort. To see the process :
/* ... */
int *merged=mergesort(array,size);
//Call to mergesort
//Creation of scope A
/* ... */
int merger[size]; //Allocation of memory for 'merger' in scope A
/* ... */
return merger; //Affect the location of 'merger' to location pointed by 'merged' in previous scope
//Deletion of scope A (including deallocation of 'merger')
// Now 'merged' points to location of 'merger' which is a deallocated variable :
//no guarantees of the data stored at this location
So it is why there is a problem in your code. One way to correct it is by allocate manually some space for your variable : variables allocated manually have to be deallocated manually, so they will not be deallocated when destroying a scope. Actually the implementation inside the function is using the c++ keyword new : int *merger = new int[size];.
By replacing this declaration your code will be running : but be careful : here's an other rule, if you're using somewhere the keyword new you have to use delete somewhere else : manual allocation have to be followed by manual deallocation. So at the end of your main function, you have to add delete[] merged;. In this way there's no trouble ;) .

Try to use llvm LoopPass to find number of loops in program

I am trying to write a llvm pass program to count the number of loops within a program. Then I find LoopPass, which is explained in following link:
http://llvm.org/docs/WritingAnLLVMPass.html#the-looppass-class
Three functions are mentioned: doInitialization, runOnLoop, doFinalization.
I originally consider that "doInitialization" runs once at the start of program, "runOnLoop" runs for each time a loop is finished, and "doFinalization" runs at the end of program. I want to define a variable as counter, to be set to "0" in "doInitialization", count++ in "runOnLoop", and output result in "doFinalization".
Here is my code (partial):
virtual bool doInitialization(Loop * L, LPPassManager &LPM)
{
errs() << (*(L->block_begin()))->getParent()->getName() << '\n';
count = 0;
length = 0;
return false;
}
virtual bool runOnLoop(Loop * L, LPPassManager &LPM){
count++;
for(Loop::block_iterator b = L->block_begin(), e = L->block_end(); b != e; b++)
{
length++;
}
return false;
}
virtual bool doFinalization()
{
errs() << "# of loops: " << count << '\n';
errs() << "average depth of loop: " << (float)(length)/count << '\n';
return false;
}
But from the result, "doInitialization" seems to work for number of times equal to number of loops in one function, "runOnLoop" works as expected, "doFinalization" seems to work at the end of a function. So I get two problems:
Why should "doInitialization" works multiple times?
If I want to get the total number of loops within a program (a program may have many functions, I do want "doFinalization" works only once for a program), what should I do?
Thanks to all relative answers,
Why is doInitialization called multiple times?
Counting all loops within the program I would write a ModulePass and overwrite its runOnModule(). Module M you can access all functions (I think the begin and end function should return appropriate iterators).
Then I can use getAnalysis() to get a LoopInfo object for the specified function. That object provides iterators to iterate over all top-level loops. If such a loop contains nested loops all nested loops of the "second level" can be retrieved by using getSubLoops. So for nested loops you would have to use that getSubLoops recursivly until no more subloops exist. Then I could increase some counter for each loop object. So it would look like this (I know that code is not compiling):
int loopcounter;
void handleLoop(Loop *L) {
++loopcounter;
for (Loop *SL : L->getSubLoops()) {
handleLoop(SL);
}
}
virtual bool runOnModule(Module&M) {
loopcounter = 0;
for (auto &IT = M.begin, END = M.end(); IT != END; ++IT) {
LoopInfo &LI = getAnalysis<LoopInfo>(*IT);
for (LoopInfo::iterator LIT = LI.begin(), LEND = LI.end(); LIT != LEND; ++LIT) {
handleLoop(*LIT);
}
}
DEBUG(errs() << "Found " << loopcounter << " loops.\n");
}
To make the getAnalysis call work properly you will have to overwrite the getAnalysisUsage() and add a dependency to LoopInfo by calling AU.addRequired<LoopInfo>().
Because the loop pass is not initialized once for an entire compilation, it's initialized everytime you analyze a loop.
I'd add a debug statement to an existing loop pass that prints something unique, then use grep -c on the output of a compliation with -debug-only=<pass_you_modified>

A function is outside main,it requires use of a variable how do use it?

My function is outside main()
it's this
void Ydisplay(int D1[])
{
for(int i=0;i<a;i++)
{
cout<<"\t<<D1[i];
}
the array D1 is a dynamic array
the error is 'a' is undefined it's taken from user so it has to be in main..
but is there any other option?
You have to pass the array size along as a function parameter:
void Ydisplay(std::size_t len, int D1[])
{
for (std::size_t i = 0; i != len ;++i)
{
std::cout << '\t' << D1[i];
}
}
In C++, you would use a std:vector<int>, though.
void Ydisplay(std::vector<int> const & D1)
{
for (int n : D1)
{
std::cout << '\t' << n;
}
}
a is not know to function Ydisplay() it is local to main(), Pass value a from main.
change function syntax as:
void Ydisplay(int D1[], int a)
^ add
A syntax error, missing ":
cout<<"\t" <<D1[i];
// ^ added
Have your function in this way.,
void Ydisplay(int D1[])
{
cin >> a; //Remove getting input from main()
for(int i=0;i<a;i++)
{
cout<<'\t'<<D1[i];
}
I think you need to understand what you are trying to do. In this particular code, You are trying to print elements that are in the array D1. So you print the element starting from D1[0] to D1[n]. You use the for loop to traverse through each element in the array D1. int i starts at i = 0 to the last element which is i < sizeof(D1)/sizeof(int). You don`t need variable a, it make no sense with what you are trying to do. To print on each line try: cout << D1[i] << endl;

Multiple return value method fails with goto statements

The following code:
#include <cstdlib>
#include <iostream>
using namespace std;
int function(void)
{
static int i,state=0;
switch(state)
{
case 0: goto labeL0;
case 1 :goto labeL1;
}
labeL0:
for (i = 0; i < 10; i++)
{
state=1;
return i;
labeL1:;
}
}
int main(int argc, char *argv[])
{
cout << function() << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
fails. I mean it returns only 0 instead of 0,1,2,...
I wanted just use label and goto statements to implement such functions. It is for practice (let's say homework), but I can't get it to work. Is this even possible?
How can I use goto and label statements so that this function prints 0 1 2... so on?
It's not clear to me exactly what you're trying to do. If your goal is
jsut to use goto, the simplest solution is to implement the algorithm
exactly as you'ld normally do, replacing looping constructs wit goto;
i.e. instead of:
for ( int i = 0; i < 10; ++ i ) {
std::cout << i << std::endl
}
you could write:
int i = 0;
goto label1:
label2:
std::cout << i << std::endl;
++ i;
label1:
if ( i < 10 ) goto label2;
Back in the old days, with Fortran IV, this is what we actually did.
There's absolutely no reason to do it today (except maybe obfuscation).
I wonder, however, given the static variables, if you're not trying to
implement some sort of co-routine; that each time you call the function,
you output one higher than the previous time. In this case, I'd
recommend maintaining the state in a class, rather than using static
variables. In addition the function will need some sort of return value
so that the caller will know when it's finished, and the caller will
have to loop. Something like the following should do the trick:
class CoRoutine
{
int i;
public:
CoRoutine() : i( 0 ) {}
bool function()
{
if ( i < 10 ) {
std::cout << i <<std::endl;
++ i;
}
return i < 10;
}
};
int
main()
{
CoRoutine c;
while ( c.function() ) {
}
return 0;
}
(There's still no need for goto, of course.)
This won't work since after the return statement, the compiler leaves the function ignoring all statements after it.
Also, using labels is ugly, horrible and unmaintainable. Why are you using them? Do you want the maintenance guy arriving at your house with a chain-saw?
After executing the return statement the execution returns from function().....
So initially when i=0, "return i" returns 0 and it is displayed on screen
You should use recursive call to function to get it executed and more over your use of GOTO is a typical example of why we should avoid using goto.
void function(void)
{
static int i=0;
for(;i<10;)
{
cout<<i;
i++;
function();
}
}
void main()
{
function();
}
but if you still want to use goto statements then use this
void function(void)
{
static int i =0;
lablelA:
cout<<i;
i++;
if(i == 10)
return;
goto lablelA;
}
Jumping to labeL1 is jumping in a loop with uninitialized variable i. How could this go right? This is only 1 of the reasons to avoid goto.
EDIT: actually, it should probably work as some sort of poor man's generator (because of the static local variables), but still the case of i >= 10 should be handled. Now it is returning nothing. So your main concern in the code is that you need a loop in main to call function maximum 10 times.
Still, this is not a construct I would want to see in real code.
The code reminds me of Coroutines in C.
To print 0, 1, etc you should call the function several times. That's the whole point.