Reputation: 37
I've been learning C++ for a bit and tried my hand at making a simple function that returns the area of a room. The return statement doesn't output the value, however using cout I can see the result. Am I missing something here?
#include <iostream>
using namespace std;
int Area(int x, int y);
int main()
{
int len;
int wid;
int area;
cout << "Hello, enter the length and width of your room." << endl;
cin >> len >> wid;
cout << "The area of your room is: ";
Area(len, wid);
return 0;
}
int Area(int len, int wid)
{
int answer = ( len * wid );
return answer;
}
Upvotes: 2
Views: 1602
Reputation: 6317
return
doesn't print anything, and you shouldn't expect it to. All it does is return a value from the function. You can then do whatever you want with that value, including printing it, or assigning it to a variable:
// Does not print:
Area(len, wid);
// Does print:
int result = Area(len, wid);
std::cout << result << "\n";
// Does print:
std::cout << Area(len, wid) << "\n";
Imagine the chaos if every function in a massive codebase suddenly started printing its return value...
Upvotes: 7
Reputation: 543
std::cout
is used to print data on screen. Functions only return values, so the Area
function will return the value which is to be passed in std::ostream::operator<<
function to print it. You need to write:
std::cout << Area(len, wid) << "\n";
Upvotes: 8