Week 4
Week 4
Functions are reusable blocks of code that perform a specific task. In C++, functions help
organize programs, making them more modular, readable, and maintainable.
A function declaration (or prototype) specifies the function's name, return type, and parameters
without providing the actual implementation. It tells the compiler that the function exists.
Syntax:
Example:
b. Function Definition
A function definition provides the actual body of the function, where the logic or task of the
function is implemented.
Syntax:
Example:
c. Function Calling
To use a function, you call it by specifying its name and passing any required arguments.
Syntax:
Example:
Complete Example:
2. Function Parameters and Return Types
Parameters: Functions can take inputs in the form of parameters (also called arguments).
They are specified inside parentheses when declaring and defining the function.
o Example: int add(int a, int b) has two parameters of type int.
Return Type: The return type specifies what kind of value the function will return. If a
function does not return any value, its return type is void.
o Example: int add(int a, int b) returns an integer.
3. Function Overloading
Function overloading allows you to define multiple functions with the same name but with
different parameter lists (either in number or type of parameters). This provides flexibility in
calling functions with different types or numbers of arguments.
Syntax:
Example:
4. Default Arguments
Default arguments allow you to provide default values for function parameters. If no value is
provided when the function is called, the default value is used.
Syntax:
Example:
return a * b;
}
int main() {
std::cout << "Product: " << multiply(5) << std::endl; // Uses default value for b (2)
std::cout << "Product: " << multiply(5, 3) << std::endl; // Uses the provided value for b (3)
return 0;
In this example, if only one argument is passed to multiply, the second parameter b defaults to
2.
5. Inline Functions
Inline functions are those that are expanded in line when invoked, meaning the compiler replaces
the function call with the actual function code to eliminate the overhead of function calls. This
can improve performance for small, frequently called functions.
Syntax:
Example:
Note: The inline keyword is just a suggestion to the compiler. The compiler may choose to
ignore it if the function is too complex or if inlining would not result in performance benefits.
Conclusion
Function Declaration specifies the function’s name, parameters, and return type.
Function Definition contains the actual code to perform the task.
Function Calling is when the function is used in the program.
Function Overloading allows multiple functions with the same name but different
parameters.
Default Arguments enable setting default values for parameters.
Inline Functions are small functions that the compiler expands at the point of call,
reducing function call overhead.