chrisd1120
chrisd1120

Reputation: 25

Calling a Method Multiple Times (C++)

so, i have a main method

int main () {
 int x = 0;
 inc(x);
 inc(x);
 inc(x);
 std::cout << x << std::endl;
}

I'm trying to get my output to be '3' but can't figure out why everytime inc(x) is called x resets to 0.

my inc method:

int inc(int x){
    ++x;
    std::cout << "x = " << x << std::endl;
    return x;
}

my output:

    x = 1
    x = 1
    x = 1
    0

Why does x reset after every call to inc(x) and how can i fix this without editing my main function

Upvotes: 0

Views: 38

Answers (3)

Reginol_Blindhop
Reginol_Blindhop

Reputation: 355

If you want x to be changed you need to pass it by reference and not as a value. Also inc() would need to return void for that to make sense. here is an example.

// adding & before x passes the reference to x
void inc(int &x){
    ++x;
    std::cout << "x = " << x << std::endl; 
}
int main() {
    int x = 0;
    inc(x);
    inc(x);
    inc(x);
    std::cout << x << std::endl;
}

this prints

x = 1
x = 2
x = 3
3

Upvotes: 0

Brian
Brian

Reputation: 1248

You're passing "x" to inc() by value, so changes made in inc() won't be visible in main().

Upvotes: 0

John Wu
John Wu

Reputation: 52230

Instead of

inc(x);

I think you need

x = inc(x);

You may slap your head now.

Upvotes: 1

Related Questions