How to Create Function in C++: Syntax and Examples
In C++, you create a function by specifying its
return type, name, and parameters inside parentheses, followed by a block of code in curly braces. For example, int add(int a, int b) { return a + b; } defines a function named add that returns the sum of two integers.Syntax
A function in C++ has these parts:
- Return type: The type of value the function gives back (like
int,void,double). - Function name: The name you use to call the function.
- Parameters: Inputs inside parentheses, each with a type and name. Can be empty
()if no inputs. - Function body: Code inside curly braces
{ }that runs when the function is called.
cpp
return_type function_name(parameter_type1 parameter1, parameter_type2 parameter2, ...) {
// code to execute
return value; // if return_type is not void
}Example
This example shows a function add that takes two integers and returns their sum. The main function calls add and prints the result.
cpp
#include <iostream> int add(int a, int b) { return a + b; } int main() { int result = add(5, 3); std::cout << "Sum is: " << result << std::endl; return 0; }
Output
Sum is: 8
Common Pitfalls
Common mistakes when creating functions in C++ include:
- Forgetting the return type or using
voidwhen you need to return a value. - Not matching the return type with the actual returned value.
- Missing parentheses
()after the function name. - Not providing a return statement in a non-
voidfunction. - Using wrong parameter types or forgetting parameter names.
cpp
/* Wrong: Missing return type and parentheses */ // add { return a + b; } /* Correct: */ int add(int a, int b) { return a + b; }
Quick Reference
Remember these tips when creating functions:
- Always specify the return type before the function name.
- Use parentheses
()even if there are no parameters. - Use curly braces
{ }to enclose the function code. - Return a value if the return type is not
void. - Keep function names clear and descriptive.
Key Takeaways
Define a function with a return type, name, parameters, and a code block.
Use parentheses for parameters and curly braces for the function body.
Return a value if the function's return type is not void.
Avoid common mistakes like missing return type or return statement.
Name functions clearly to describe their purpose.