firelitte
firelitte

Reputation: 53

updating variable between functions in c++

My main program is to generate a random number to create movement of a object in a 2 dimensional array and to keep track of it.

one of my function void current_row(int row){position = row}; keeps track of the current row of the object.

since the variable is not global. i am finding problems calling the current location and updating it to the next movement. this is how the other function may look like:

void movement (){
    int row;
    row = current_row();
    /*
     * Here is the problem i'm having. This may well be 
     * a third function which has the same information 
     * as my first function. But still how do I access
     * once without modifying it and access it  
     * again to update it?
     */

    // call another function that creates new row.
    // update that info to the row
}

i am new to c++.

Upvotes: 0

Views: 1792

Answers (2)

serj
serj

Reputation: 508

In case it's an OOP environment (as C++ tag implies), some class should declare int row as a class member (including a getter and a setter as methods).

Another option is declaring the variable at the head of the main() part of the program and call functions with row as a function parameter.

void movement(int row) {

}

You can consider the parameter be passed by reference if you are intending to change it, otherwise it would be better declaring it const inside the function parameter declaration. If part of the answer sounds unfamiliar to you I would suggest reading through : What's the difference between passing by reference vs. passing by value?

Upvotes: 0

Hrishi
Hrishi

Reputation: 7138

Use an instance variable to keep track of it. That's why instance variables exist: To hold their values between function calls.

Upvotes: 1

Related Questions