Return values in function (C++)
Go to solution
Solved by Unimportant,
3 minutes ago, Atalia Chez said:<snip>
A function is simply a subroutine that can be called from another piece of code and optionally takes parameters (input values) to work with and, optionally, returns a value (output value).
int sum(int firstnum, int secondnum) // ^1 ^2 ^3 ^4 ^5 ^6
Declares a function called sum (2), that takes 2 parameters by value, the first parameter of type int (3), called firstnum (4). The second parameter also of type int (5), called secondnum (6).
The function returns a int (1).
Taking parameters by value means firstnum and secondnum will be copies of the original parameters passed to the function when it's called.
int sum(int firstnum, int secondnum) { //Define a new variable of type int, called 'result', which is initialised to 0. //This variable will only exist from now on and until the end of function sum. When the function returns it ceases to exist. int result=0; //Add firstnum and secondnum together and assign the result to the variable 'result' result=firstnum+secondnum; //Return a copy of the value in variable 'result' to the caller. return result; } //the 'main' function, taking no parameters, and returning a int to the operating system, known as the 'exit code' int main() { //Create new variable of type int called 'multiply', which is initialised to 2. int multiply=2; //Create new variable of type int called 'mainResult', which is uninitialised. (contains garbage) int mainResult; //Call the function/subroutine called 'sum', and pass it the parameters 253 as 'firstnum' and 456 as 'secondnum'. //The result, which 'sum' returns, will be multiplied with variable 'multiply'. //The result of that is assigned to variable 'mainResult' mainResult=multiply*sum(253,456); //return 0 to OS, indicates success. return 0; }
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now