×
>
<

C++ Programming

C++ Functions | CrackEase

C++ Functions

Functions

Instead of repeating the same code multiple times, group it into a named block and reuse it wherever needed.

Definition: A function is a named block of code that performs a specific task and can be reused.

A function can be called any number of times from different parts of the program.

Types of Functions
function types

1. Predefined (library) functions

  • These functions are already defined in standard libraries and provided to the programmer.
  • Use them instead of writing your own implementation. Example: pow() in <cmath>, printf() in <cstdio>.

2. User-defined functions

  • These are written by the programmer to perform specific tasks.
  • Example: int add(int a,int b).
Function Components

To write and use functions you should understand these components:

1. Function declaration (prototype)

  • The prototype tells the compiler the return type, number and types of parameters, and name of the function.
  • It can appear before main() or in a header; it must appear before the function is called if the definition comes later.

Syntax:

  
return_type func_name(arg1_type, arg2_type, ...);
  

Example:

  
int sum(int, int);
  

This prototype indicates a function that takes two int arguments and returns an int.

2. Function definition

  • The definition contains the actual statements that implement the function's task.
  • The return type in the definition must match the prototype's return type.

Example :

  
int sum(int x, int y) // function definition
{
    return x + y;
}
  
3. Function call

  • A function call requests execution of the function's code.
  • Do not specify the return type at the call site.

Example :

  
sum(2, 3); // valid
// int sum(2,3); // invalid
  
4. Formal parameters

  • Parameters declared in the function definition are formal parameters.
  • They receive values from the actual parameters supplied at the call site.

Example :

  
int sum(int x, int y) // x and y are formal parameters
{
    return x + y;
}
  
5. Actual parameters

  • These are the values or expressions passed to the function when calling it.
  • They can be literals, variables, or expressions.

Example :

  
sum(2, 3);   // literals
sum(x, y);   // variables
sum(2 * 3, 7 - 2); // expressions
  
6. Return statement

  • The return statement provides a value back to the caller and exits the function.
  • Its type must match the function's declared return type (except for void functions which may use return; to exit early).

Example :

  
int sum(int, int);
float sumf(int, float);
long fact(int);
  
  
#include <iostream>
using namespace std;

int demo() // function definition
{
    cout << "control acquired from main\n";
    return 1;
}

int main()
{
    cout << "before call control under main\n";
    cout << "control transferred from main to demo\n" << demo() << '\n';
    cout << "control returned back from demo to main()\n";
    return 0;
}
  
output
  
before call control under main
control transferred from main to demo
control acquired from main
control returned back from demo to main()
  

  • The call demo() transfers control to demo, and return 1 returns control (and value) back to the caller.
  • A void function cannot return a value; it may use return; to exit early.

  
void add()
{
    // return a + b; // error: void cannot return a value
}
  
7. Calling function (caller)

The caller is the function that invokes another function.

Example :

  
int main()
{
    add(2, 3); // main() calls add()
    return 0;
}
  
8. Function signature

The signature is the function name plus the parameter types (order matters). It excludes the return type.

Example :

  
int add(int x, int y)
{
    return x + y;
}
// Signature: add(int, int)
  
Functions can be classified in 4 ways
No arguments passed and no return value
  
#include <iostream>
using namespace std;

void prime(); // prototype

int main()
{
    prime(); // function call without arguments
    return 0;
}

void prime()
{
    int num, i, flag = 0;
    cout << "Enter a positive integer to check: ";
    cin >> num;
    for (i = 2; i <= num / 2; ++i)
    {
        if (num % i == 0)
        {
            flag = 1;
            break;
        }
    }
    if (flag == 1)
        cout << num << " is not a prime number.";
    else
        cout << num << " is a prime number.";
}
  
output
  
Enter a positive integer to check: 3
3 is a prime number.
  

  • In the above program, prime() is called from main() with no arguments.
  • prime() reads a number and prints whether it is prime. It returns no value (void).

No arguments passed but a return value
  
#include <iostream>
using namespace std;

int prime(); // prototype

int main()
{
    int num, i, flag = 0;
    num = prime(); // function returns an int
    for (i = 2; i <= num / 2; ++i)
    {
        if (num % i == 0)
        {
            flag = 1;
            break;
        }
    }
    if (flag == 1)
        cout << num << " is not a prime number.";
    else
        cout << num << " is a prime number.";
    return 0;
}

int prime()
{
    int n;
    cout << "Enter a positive integer to check: ";
    cin >> n;
    return n;
}
  
output
  
Enter a positive integer to check: 12
12 is not a prime number.
  
Arguments passed but no return value
  
#include <iostream>
using namespace std;

void prime(int n); // prototype

int main()
{
    int num;
    cout << "Enter a positive integer to check: ";
    cin >> num;
    prime(num); // pass num to prime()
    return 0;
}

void prime(int n)
{
    int i, flag = 0;
    for (i = 2; i <= n / 2; ++i)
    {
        if (n % i == 0)
        {
            flag = 1;
            break;
        }
    }
    if (flag == 1)
        cout << n << " is not a prime number.";
    else
        cout << n << " is a prime number.";
}
  
output
  
Enter a positive integer to check: 7
7 is a prime number.
  
Arguments passed and a return value
  
#include <iostream>
using namespace std;

int prime(int n); // prototype

int main()
{
    int num, flag = 0;
    cout << "Enter positive integer to check: ";
    cin >> num;
    flag = prime(num); // function returns 1 if not prime, 0 if prime
    if (flag == 1)
        cout << num << " is not a prime number.";
    else
        cout << num << " is a prime number.";
    return 0;
}

int prime(int n)
{
    int i;
    for (i = 2; i <= n / 2; ++i)
    {
        if (n % i == 0)
            return 1;
    }
    return 0;
}
  
output
  
Enter positive integer to check: 5
5 is a prime number.
  

  • Choose the function style depending on the problem and how you prefer to pass and receive data.

Some Rules and Advantages

  • Debugging: Errors are easier to isolate because they are confined to a module (function).
  • Reusability: Functions enable reuse of code without rewriting it.

Is main() user-defined or predefined?

main() is a user-defined function: the programmer writes its body, but its signature is defined by the language runtime.

  
#include <iostream>
using namespace std;

int main()
{
    cout << "size: " << sizeof(main) << endl;
    return 0;
}
  
output (platform dependent)
  
size: 1
  

Note: printing sizeof(main) is non-portable and only for demonstration; behavior may vary by implementation.

Function Scope
  
#include <iostream>
using namespace std;

void demo()
{
    int a = 5;
    cout << "a: " << a << endl; // valid: 'a' is inside demo()
}

int main()
{
    // cout << "a:" << a << endl; // Error: 'a' was not declared in this scope
    demo(); // call demo()
    return 0;
}
  
output
  
a: 5
  

  • Variables declared inside a function are local to that function and not accessible outside.
  • Use appropriate scope for variables depending on intended visibility.

Infinite Recursion in Function

Recursive functions must have a base case; otherwise they cause infinite recursion (and eventually stack overflow).

  
#include <iostream>
using namespace std;

void display()
{
    cout << "This will create infinite recursion" << endl;
    display(); // recursive call without base case -> infinite recursion
}

int main()
{
    display();
    return 0;
}
  
output (conceptual)
  
This will create infinite recursion
This will create infinite recursion
... (continues until stack overflow)
  

  • Always ensure recursion has a terminating condition to avoid infinite recursion.

Footer Content | CrackEase