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;
}
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;
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
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With