OvercomeSupreme
OvercomeSupreme

Reputation: 31

Can't print the right result

I wanted to get the program to calculate the cube of a number by using a pointer. Here's my code, what is wrong with it? the expected out put should be 5 and 125, while i get 5 and a random number

using namespace std;

int cubeByreference(int *);
int main()
{

    int number = 5;
    cout<<"The original value of number is "<< number ;
    number = cubeByreference( &number);
    cout<<"\nThe new value of number is "<< number<<endl;

    return 0;
}

int cubeByreference(int *nPtr)
{
    *nPtr = *nPtr * *nPtr * *nPtr;
}

Upvotes: 0

Views: 42

Answers (1)

cigien
cigien

Reputation: 60228

You need to return the value from the function:

int cubeByreference(int *nPtr)
{
    *nPtr = *nPtr * *nPtr * *nPtr;
    return *nPtr;
}

Otherwise, you invoke undefined behavior. (number will have some undetermined value if you don't return, which could be the cause of the random output).

Note that this could just be a void function, since you are changing the argument. There's no need to "return" a value in 2 different ways.

Also, to avoid the pointers (and the associated syntax), you could take the argument by reference:

void cubeByValue(int &n)
{
    n = n * n * n;
}

Better still, change the function so that it accepts the argument by value. It makes the function easier to implement and use.

int cubeByValue(int n)
{
    return n * n * n;
}

Upvotes: 4

Related Questions