MOCKSTACKS
EN
Questions And Answers

More Tutorials








C++ Create function with parameters

In C++ when creating a function we might need to pass parameters as it represents a necessary information to function to perform the work.

C++ Create function with parameters syntax

return_type myFunction(paramater1_type parameter1, paramater2_type parameter2, ...) {
  // code to be executed
}

C++ example of Create function with parameters


In the below example we are going to create a function called: doSum(int val1, int val2) This function takes 2 parameters and does the sum and return the value to main() function

#include <iostream>

using namespace std;

int doSum(int val1, int val2) {
  return val1 + val2;
}

int main() {
  cout << doSum(2, 3);
  return 0;
}

Output

5

Another C++ example of Create function with parameters


In the below example we are going to create a function called: tellMeYourAge(int val1, string val2) This function takes 2 parameters and creates a message then return it to main() function.

Note: to_string() function will be discussed in C++ Type cast. But for now you will need to know that this function convert an integer number which is age to a string so we ca concatenate it with the returned message.

#include <iostream>

#include<string>

using namespace std;

string tellMeYourAge(int age, string name) {
  return name + " age is: " + to_string(age);
}

int main() {
  cout << tellMeYourAge(35, "Jhon");
  return 0;
}

Output

Jhon age is: 35

Conclusion

In this page (written and validated by ) you learned about C++ Create function with parameters . What's Next? If you are interested in completing Cpp tutorial, your next topic will be learning about: Cpp function overloading.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.