0

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

3 Answers 3

1

Instead of

inc(x);

I think you need

x = inc(x);

You may slap your head now.

Sign up to request clarification or add additional context in comments.

1 Comment

That requires that he change main() - his question specifies that he not do that.
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.