user2812990
user2812990

Reputation: 3

C++ Return Statement Not Working

I've just started learning C++ and i've been having problems implementing return statements. I've been easily able to pass data to a new function but I am having no joy in getting it to return.

I've written the simplest code I could think of to try and debug what is going wrong and I still can't work it out. I am NOT trying to pass too many return values and I have a correct function type to pass too. It just doesn't seem to work?

I am using Xcode 4 on a Macbook Pro:

#include <iostream>
using namespace std;

int agenext (int age);

int main ()
{   int age;
    cout << "What's Your Age? \n";
    cin >> age;
    cout << "Your Current Age: " << age;
    agenext(age);
    cout << endl << "A year has passed your new age is: ";
    cout << age;
}

int agenext (int x)
{
    x++;
    cout << endl << "Your Next Birthday is " << x;
    return x;
}

Upvotes: 0

Views: 6330

Answers (4)

Hoang Minh
Hoang Minh

Reputation: 1220

In your main function, you need another variable to hold the new age that is return from the age function.

int main ()
{   int age, newAge;
    cout << "What's Your Age? \n";
    cin >> age;
    cout << "Your Current Age: " << age;
    newAge = agenext(age);
    cout << endl << "A year has passed your new age is: ";
    cout << newAge;
    return 0;
}

Upvotes: 0

StilesCrisis
StilesCrisis

Reputation: 16290

Both the existing answers are correct; if you want to return a value, it needs to be assigned somewhere.

For future reference, you can also do what you want by skipping the return and passing age by reference instead of value.

void agenext (int &x)
{
    x++;
    cout << endl << "Your Next Birthday is " << x;
    /* the value change WILL show up in the calling function */
}

Upvotes: 2

Obicere
Obicere

Reputation: 3019

It's returning perfectly find. You just aren't setting the value it returns to anything.

age = agenext(age)

Is what you are looking for, or you could pass a pointer or a reference to the age variable.

Upvotes: 4

jedwards
jedwards

Reputation: 30200

returning is only half the battle, the other half is assigning that value to something. Consider changing:

agenext(age);

to

age = agenext(age);

Upvotes: 3

Related Questions