2

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;
}
  • 1
    Can you please copy-paste the output you get from running that program, because there should not be any output from calling `Area`. – Some programmer dude May 17 '18 at 11:45
  • just a typo, perhaps you mean: `cout << "The area of your room is: " << Area(len, wid);` – Joseph D. May 17 '18 at 11:47
  • 3
    @codekaizer I think this is not a typo, let me explain. I've seen multiple time students unable to grasp the conceptual difference between returning a value and printing a value. This is due, I think, to poor education regarding development to beginners: they are often asked to "return" the result of a computation by printing it on screen. Those exercises are often written as a relatively short but monolithic `main()`. Hence the confusion between `return` and `std::ostream::operator<<`. – YSC May 17 '18 at 12:12
  • 1
    There are many terms that refer to different things in different contexts. One distinction that can be confusing at first is that between a *function's* "output", which usually means the value that the function returns to its caller, and a *program's* "output", which is the things that are printed on the terminal. – molbdnilo May 17 '18 at 12:18
  • @YSC, i agree with you. – Joseph D. May 17 '18 at 12:20

2 Answers2

8

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";
YSC
  • 38,212
  • 9
  • 96
  • 149
mayank
  • 543
  • 4
  • 14
  • do you mind my edit? If you do, you can improve it or rollback it. Hope its good. – YSC May 17 '18 at 12:15
7

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...

hlt
  • 6,219
  • 3
  • 23
  • 43