0

Hello i am totally new to c++ programming, I had a question when we use a int function why do we have to use return command like we can use cout << sum << endl; and call the function in main(). but for return we have to do like cout << printSum();

Case 1:

#include <iostream>
using namespace std;

int addNumbers(int x, int y){
    int sum = x + y;
    cout << sum << endl;
}

int main() {
    addNumbers(4, 5);
    return 0;
}// without using  return

Case 2:

#include <iostream>
using namespace std;

int addNumbers(int x, int y){
    int sum = x + y;
    return sum;
}

int main() {
    cout << addNumbers(4, 5) << endl;
    return 0;
}// return method
MechMK1
  • 3,278
  • 7
  • 37
  • 55
Ishaan Shah
  • 49
  • 1
  • 5
  • You must return int because the function return type is int. If you want just to output it with cout, you should put "void addNumbers(int x, int y)" – aleksandar Jul 02 '15 at 16:30
  • You need to read a C++ text, specifically about "functions". A function must `return` a value of the type that it is declared. So `int addNumbers(int x, int y)` Must accept two `int` arguments, and `return` an `int`. https://stackoverflow.com/questions/1610030/why-can-you-return-from-a-non-void-function-without-returning-a-value-without-pr – Cory Kramer Jul 02 '15 at 16:30
  • ***void*** methods don't ***return***. All others do. – David Corbin Jul 02 '15 at 16:31
  • 3
    @DavidCorbin: Nitpicking: All functions **return**. Functions declared as **void** don't *return a value*. You can put an empty return statement in a function. – Thomas Matthews Jul 02 '15 at 16:40
  • @CoryKramer I don't find the related stuff in `8.4`, `C++11`, maybe I am looking at wrong chapter? – Natasha Dutta Jul 02 '15 at 16:41
  • @CoryKramer actually I expect something similar to `C11`, chapter `§6.9.1/12` – Natasha Dutta Jul 02 '15 at 16:43
  • @ThomasMatthews True. It's easier to explain that ***void*** methods don't return :) – David Corbin Jul 02 '15 at 16:46
  • @DavidCorbin Beware, don't say `void methods don't return`, people like me (2 years' previous version) will ask a follow up question, _"does that mean it has an infinite lop at the end of the function?"_ :P – Natasha Dutta Jul 02 '15 at 16:48
  • @ThomasMatthews Can you please comment on my earlier comment, i'm clueless, and this standard draft is printed in a font not suitable for my eyes... grrr... – Natasha Dutta Jul 02 '15 at 16:50
  • @NatashaDutta: The concept is about *data* vs. *execution*. A function *declared* with a type, such as `int My_Function()`, tells the compiler that the function will return data. A function declared as `void Your_Function()`, tells the compiler it returns *nothing* as in a *void*. As far as execution, most functions return back to the caller. Some functions don't return, and either have endless loop, terminate the program or shut down the machine. These are exceptions, and not as popular (they do exist in the embedded systems arena). HTH. – Thomas Matthews Jul 02 '15 at 17:04
  • @ThomasMatthews I think I did not make myself clear....did you check the `C11` equivalent? I was asking about a missing `return` statement before the closing `}`. IN C it's UB, if th rturn value is used afterwards. What does C++11 has to say about that? – Natasha Dutta Jul 02 '15 at 17:07
  • @NatashaDutta: There are already questions on StackOverflow about not returning data in a function that says it should. You should research them. – Thomas Matthews Jul 02 '15 at 17:08

4 Answers4

1

The int function must return an int. If you don't want to return values, you can use a void function:

#include <iostream>
using namespace std;

void addNumbers(int x, int y){
    int sum = x + y;
    cout << sum << endl;
}

int main() {
    addNumbers(4, 5);
    return 0;
}

The main() must return int (standard), which means that the program ran successfully (0). You can even leave the return statement out of main(), but it will return zero (implicit).

#include <iostream>
using namespace std;

void addNumbers(int x, int y){
    int sum = x + y;
    cout << sum << endl;
}

int main() {
    addNumbers(4, 5);
}
antonioduarte
  • 655
  • 7
  • 19
1

return statement is seemingly very basic, but in fact, one of the most puzzling aspects of procedural programming for freshman students in our local university.

What are the functions anyway?

Functions are the building blocks of procedural and functional programming languages. You might think of a function as of reusable, maintainable block of code responsible for some action. If you perform some operations often together, you might want to "pack" them inside a function. A "good" function is a little machine that takes some input data and gives back processed data. In C++ you can "share" the results of the processing with "outside code" by returning a value, modifying a parameter (worse) or modifying the global state (worst).

In simple case, "returning" functions are direct analogs of math functions like y = f(x) (even the call syntax is very similar). As a programmer you just define what is x, what is y and how exactly f maps x to y.

Printing vs returning

Now, the printing into console (terminal) and returning are not the same. In simple words, printing is just showing the user some characters on the screen ("speaking with user"). Returning from function allows to receive the result from function ("speaking with outside code"), but it's invisible for the user unless you print it afterwards .

Different function layouts you may encounter while learning

(does not pretend to be an exhaustive list)

So, in your class or tutorial sometimes they teach you how to

(1) print an object directly within main()

int main() {
    int i = 42 + 13;
    std::cout << i << std::endl;
}   

(2) print an object inside a function

void printSum(int a, int b) {
    int i = a + b;
    std::cout << i << std::endl;
}

int main() {
    printSum(42, 13);
}

(3) return an object from the function and printing afterward

void sum(int a, int b) {
     return a + b;
}

int main() {
    int s = sum(42, 13);
    std::cout << s << std::endl;
}   

Obviously, (1) is not reusable at all: to change parameters you must intervene into the program logic. Also, if logic is something more than just a sum, main() function will grow quickly in size and become unmaintainable. Responsibilities will be scattered across the code, violating Single responsibility principle

(2) is better in all aspects: function encapsulates logic in a separate place in code, has distinctive name, can be changed separately from main function. Function can be called with different values, and changing arguments doesn't change the function.

But it still has 2 responsibilities: perform the calculation and output to the screen. What if you want not to print the result, but write it to a file? or send it via network? or just discard it? You will need to write another function. The logic inside this new function will be the same, thus introducing duplication and violating DRY principle. Also, (2) is not a pure function because it is modifying std::cout which is basically the global state (we say that this function has "side effects").

Also, you can think about (2) as if it was (1), but with whole program logic moved from main() into a separate function (that's why sometimes functions are called "subprograms").

(3) solves the multiple responsibility problem, by getting rid of printing (moving it into the "user code"). The function contains only pure logic. Now it's a number crunching machine. In main function you can decide what to do with the result of the calculations without touching the calculating function. It becomes a "black box". No need to worry how it is implemented, and no need to change anything, it just works.

In your post there is a shorter version of (3):

int main() {
    std::cout << sum(42, 13) << std::endl;
}   

The difference is that no temporary object int s being created, but return value is being written directly to std::cout (in fact, passed as a parameter to a function called operator<<)

In real life

In real-life programming, most of the time you will be writing functions like (3), that don't print anything. Printing to terminal is just a quick and simple way to visualize data. That's why you've been taught how to output to standard streams rather than writing to the files, network sockets or showing GUI widgets. Console printing is also very handy during debugging.

See also:

P.S. There is a big deal of simplification in this post, thus the usage of lots of quoted terms.

Community
  • 1
  • 1
Ivan Aksamentov - Drop
  • 12,860
  • 3
  • 34
  • 61
0

You have two slightly different scenario in both of your snippets.

  • Case 1: You are printing the value from the called function, before the function finishes execution. So, you don't (need to) return any value. So you don't need a return statement.

  • Case 2: You are expecting the function to return the value which will get printd. So, you need to have a the return in your called function.

Natasha Dutta
  • 3,242
  • 21
  • 23
0

This is because of the return types of the function. Some times you want a function to give you a result instead of just doing things with the information you put into it.

Just like a variable has a type such as int and string, a function wants a type for the item it will be returning.

Here is a website which might help you get into the basics of functions including information about return types.

MrSansoms
  • 55
  • 1
  • 5