0% found this document useful (0 votes)
48 views6 pages

Function in C++

This document provides a comprehensive overview of functions in C++, detailing their definitions, declarations, parameter passing methods, return types, and special function types. It includes 12 illustrative examples demonstrating various concepts such as pass by value, pass by reference, function overloading, and lambda functions. The conclusion emphasizes the versatility and importance of functions in creating efficient and modular code.

Uploaded by

Amr Essam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views6 pages

Function in C++

This document provides a comprehensive overview of functions in C++, detailing their definitions, declarations, parameter passing methods, return types, and special function types. It includes 12 illustrative examples demonstrating various concepts such as pass by value, pass by reference, function overloading, and lambda functions. The conclusion emphasizes the versatility and importance of functions in creating efficient and modular code.

Uploaded by

Amr Essam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Functions in C++: Concepts and Examples

Grok
July 12, 2025

1 Introduction
Functions in C++ are reusable blocks of code that perform specific tasks. They enhance
code modularity, readability, and reusability. This document covers all aspects of func-
tions in C++, including declarations, definitions, parameter passing, return types, and
special cases, with 12 illustrative examples.

2 Key Concepts of Functions in C++


Functions in C++ are defined with a return type, name, parameter list, and body. Below
are the key concepts:

2.1 Function Declaration and Definition


• Declaration: Specifies the function’s return type, name, and parameters without
a body (e.g., int add(int, int);).

• Definition: Includes the function body with the actual implementation.

• Prototype: A declaration used in header files or before main() to inform the


compiler about the function.

2.2 Parameter Passing


• Pass by Value: Copies the argument; changes inside the function do not affect
the original.

• Pass by Reference: Passes an alias to the argument, allowing modifications.

• Pass by Pointer: Passes a memory address, allowing modifications via derefer-


encing.

• Const Parameters: Prevents modification of passed arguments (e.g., const int


&x).

• Default Parameters: Allows parameters to have default values if not provided.

1
2.3 Return Types
• Standard Types: int, double, void, etc.

• Reference Return: Returns a reference to allow modification of the returned


object.

• Auto Return (C++11): Compiler deduces the return type.

• Multiple Returns (C++11): Using std::tuple or structured bindings (C++17).

2.4 Special Function Types


• Inline Functions: Suggested to the compiler for inlining to reduce function call
overhead.

• Static Functions: Retain variable values between calls.

• Recursive Functions: Functions that call themselves.

• Function Overloading: Multiple functions with the same name but different
parameters.

• Function Templates: Generic functions for different data types.

• Lambda Functions (C++11): Anonymous functions defined inline.

• Function Pointers: Pointers to functions for dynamic function calls.

2.5 Other Features


• Constexpr Functions (C++11): Evaluated at compile-time for constant ex-
pressions.

• Noexcept Specifier (C++11): Indicates a function does not throw exceptions.

• Variadic Functions: Handle a variable number of arguments using std::va_list


or templates (C++11).

3 Examples
Below are 12 examples demonstrating various aspects of functions in C++.

3.1 Example 1: Basic Function (Pass by Value)


1 # include <iostream >
2 int add(int a, int b) {
3 return a + b;
4 }
5 int main () {
6 int result = add (5, 3);
7 std :: cout << "Sum: " << result << std :: endl;

2
8 return 0;
9 }

Output: Sum: 8

3.2 Example 2: Pass by Reference


1 # include <iostream >
2 void swap(int &a, int &b) {
3 int temp = a;
4 a = b;
5 b = temp;
6 }
7 int main () {
8 int x = 5, y = 10;
9 swap(x, y);
10 std :: cout << "x: " << x << ", y: " << y << std :: endl;
11 return 0;
12 }

Output: x: 10, y: 5

3.3 Example 3: Pass by Pointer


1 # include <iostream >
2 void swap(int *a, int *b) {
3 int temp = *a;
4 *a = *b;
5 *b = temp;
6 }
7 int main () {
8 int x = 5, y = 10;
9 swap (&x, &y);
10 std :: cout << "x: " << x << ", y: " << y << std :: endl;
11 return 0;
12 }

Output: x: 10, y: 5

3.4 Example 4: Default Parameters


1 # include <iostream >
2 void printMessage ( const std :: string &msg = "Hello ") {
3 std :: cout << msg << std :: endl;
4 }
5 int main () {
6 printMessage (); // Uses default
7 printMessage ("World ");
8 return 0;
9 }

3
Output: Hello
World

3.5 Example 5: Reference Return


1 # include <iostream >
2 int & getMax (int &a, int &b) {
3 return (a > b) ? a : b;
4 }
5 int main () {
6 int x = 5, y = 10;
7 getMax (x, y) = 20; // Modifies y
8 std :: cout << "x: " << x << ", y: " << y << std :: endl;
9 return 0;
10 }

Output: x: 5, y: 20

3.6 Example 6: Inline Function


1 # include <iostream >
2 inline int square (int x) {
3 return x * x;
4 }
5 int main () {
6 std :: cout << " Square of 5: " << square (5) << std :: endl;
7 return 0;
8 }

Output: Square of 5: 25

3.7 Example 7: Static Function Variable


1 # include <iostream >
2 void counter () {
3 static int count = 0; // Retains value
4 count ++;
5 std :: cout << "Count : " << count << std :: endl;
6 }
7 int main () {
8 counter (); // Count : 1
9 counter (); // Count : 2
10 return 0;
11 }

Output: Count: 1
Count: 2

4
3.8 Example 8: Recursive Function
1 # include <iostream >
2 int factorial (int n) {
3 if (n <= 1) return 1;
4 return n * factorial (n - 1);
5 }
6 int main () {
7 std :: cout << " Factorial of 5: " << factorial (5) << std :: endl;
8 return 0;
9 }

Output: Factorial of 5: 120

3.9 Example 9: Function Overloading


1 # include <iostream >
2 int add(int a, int b) { return a + b; }
3 double add( double a, double b) { return a + b; }
4 int main () {
5 std :: cout << "Int sum: " << add (3, 4) << std :: endl;
6 std :: cout << " Double sum: " << add (3.5 , 4.5) << std :: endl;
7 return 0;
8 }

Output: Int sum: 7


Double sum: 8

3.10 Example 10: Function Template


1 # include <iostream >
2 template <typename T>
3 T max(T a, T b) {
4 return (a > b) ? a : b;
5 }
6 int main () {
7 std :: cout << "Max int: " << max (5, 10) << std :: endl;
8 std :: cout << "Max double : " << max (3.14 , 2.71) << std :: endl;
9 return 0;
10 }

Output: Max int: 10


Max double: 3.14

3.11 Example 11: Lambda Function (C++11)


1 # include <iostream >
2 # include <algorithm >
3 # include <vector >
4 int main () {

5
5 std :: vector <int > vec = {1, 5, 3, 2, 4};
6 std :: sort(vec.begin () , vec.end () , []( int a, int b) { return a <
b; });
7 for (int x : vec) std :: cout << x << " ";
8 std :: cout << std :: endl;
9 return 0;
10 }

Output: 1 2 3 4 5

3.12 Example 12: Function Pointer


1 # include <iostream >
2 int add(int a, int b) { return a + b; }
3 int main () {
4 int (* funcPtr )(int , int) = add; // Function pointer
5 std :: cout << "Sum: " << funcPtr (5, 3) << std :: endl;
6 return 0;
7 }

Output: Sum: 8

4 Conclusion
Functions in C++ are versatile tools for structuring code. They support various parameter-
passing mechanisms, return types, and advanced features like templates and lambdas,
making them essential for efficient and modular programming.

You might also like