Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return not returning variable value

Tags:

c++

return

I wrote a practice program for my class, and everything in it works except for returning the value of a variable. My question is, why isn't it returning the value? Here is sample code I wrote out to avoid having to copy and paste large parts of code that aren't relevant.

#include <iostream>
using std::cout; using std::cin;
using std::endl; using std::fixed;

#include <iomanip>
using std::setw; using std::setprecision;

int testing();

int main()
{
    testing();

    return 0;

}

int testing() {
    int debtArray[] = {4,5,6,7,9,};
    int total = 0;

    for(int debt = 0; debt < 5; debt++) {
    total += debtArray[debt];
    }

    return total;
}
like image 729
ExpletiveDeleted Avatar asked Aug 31 '13 18:08

ExpletiveDeleted


4 Answers

In fact, the function is returning a value. However, main() is choosing to ignore that return value.

Try the following in your main():

int total = testing();
std::cout << "The total is " << total << std::endl;
like image 191
NPE Avatar answered Oct 30 '22 21:10

NPE


The function does return a value. You are not displaying the returned value on the screen so that is why you think it doesnt return a value

like image 44
Rabbiya Shahid Avatar answered Oct 30 '22 22:10

Rabbiya Shahid


testing() does return a value, but the value does not get used or saved anywhere. You are using std::cout, std::cin, std::endl, etc. but you aren't using them. I'm assuming what you wanted to do was display total. A program for that would look like:

#include <iostream>
using std::cout;
using std::endl;

int testing();

int main() {
    int totaldebt = testing();
    cout << totaldebt << endl;

    return 0;
}

int testing() {
    int debtArray[] = {4,5,6,7,9};
    int total = 0;

    for(int debt = 0; debt < 5; debt++) {
        total += debtArray[debt];
    }

    return total;
}

What is happening in your code is (assuming the compiler doesn't optimize in any way) inside main(), testing() is called, goes through its instructions, and then the program moves on. The same thing happens if you call printf from <cstdlib>. printf is supposed to return the number of characters it displays, but if you don't store the result anywhere it just displays the text and the program continues.

What I have to ask is why are you using more than you actually make use of? Or is this not the complete code?

like image 37
Cave Dweller Avatar answered Oct 30 '22 21:10

Cave Dweller


Return is not equivalent to print. If you want the value the function has returned to display to stdout, you have to have a method of doing that. This is accomplished by printing the value that was returned using std::cout and the << operator either in main or in the function itself

like image 40
smac89 Avatar answered Oct 30 '22 21:10

smac89