In C++, functions can be classified into built-in functions and user-defined functions.
Built-in Functions:
Provided by C++ or its libraries.
Already written, tested, and ready to use.
Examples:
cout(),cin(),sqrt(),pow(),strlen()
User-defined Functions:
Written by the programmer.
Custom functions to perform specific tasks.
Examples:
add(),multiply(),factorial(),greet()
Comparison Table
| Feature | Built-in Functions | User-defined Functions |
|---|---|---|
| Written by | Compiler/Programmer Library | Programmer |
| Reusability | Predefined | Customizable |
| Complexity | Already tested and optimized | Programmer needs to debug |
| Flexibility | Fixed | Fully flexible |
| Examples | sqrt(), abs(), strlen() | add(), multiply(), factorial() |
Examples of Built-in Functions
sqrt()– Calculates square root
pow()– Raises number to power
abs()– Absolute value
strlen()– Length of string
toupper()– Converts character to uppercase
Examples of User-defined Functions
Function to add two numbers
Function to calculate factorial
Function to check even or odd
Function to greet a user
Function to find maximum of two numbers
Function to calculate area of rectangle
Function to swap two numbers (pass by reference)
Function to check prime number
Function to calculate sum of array elements
Function to reverse a string
Function to print multiplication table
Function to find largest in array
Function to calculate power recursively
Function to count digits in number
Function to convert Celsius to Fahrenheit
Function to check palindrome number
Function to calculate GCD
Function to calculate LCM
Function to swap without temp variable
Function to print Fibonacci series
Best Practices for Functions
One Task Per Function: Each function should do only one thing.
Use Meaningful Names: Name functions like
calculateSum()instead offunc1().Keep Functions Small: Avoid very long functions.
Pass by Reference When Needed: For large data or arrays to improve efficiency.
Avoid Global Variables: Prefer parameters and return values.
Comment Functions: Write purpose, parameters, and return values.
Use Const Where Applicable: For data that shouldn’t be modified.
Reusability: Write functions that can be reused in multiple parts of your program.
Extra Related Concepts
Recursive Functions: Functions can call themselves.
Inline Functions: Use for small, frequently called functions.
Default Parameters: Provide default values if arguments are not passed.
Function Overloading: Same function name with different parameter types.
Return by Reference: For large objects to avoid copying.
Function Templates: Generic functions that work with multiple data types.
Common Best Practice Questions
When should you use built-in vs user-defined functions?
How can you improve efficiency when passing large arrays to functions?
Why should each function perform one specific task?
What is the difference between return by value and return by reference?
How can you avoid code duplication using functions?