Functions

Function

A function is a self-contained block of code that performs a specific task. Functions in C++ allow you to modularize your code, making it more organized, readable, and easier to maintain. You can define functions to perform tasks such as calculations, data manipulation, input/output operations, and more

How to create a function ?


To create a function in C++, you need to follow these steps:

  1. Function Declaration (Prototype): Declare the function prototype. This tells the compiler about the function’s name, return type, and parameters (if any).
  2. Function Definition: Write the actual code for the function. This is where you define what the function does.

Syntax :

void myFunction() {
  // code to be executed
}

Here’s a basic example of how to create a simple function in C++:

#include <iostream>

// Function declaration (prototype)
void sayHello();

int main() {
    // Call the function
    sayHello();

    return 0;
}

// Function definition
void sayHello() {
    std::cout << "Hello, world!" << std::endl;
}

Output:

Hello, world!

Let’s break down the steps:

  1. Function Declaration (Prototype):
    • In the above code, void sayHello(); is the function declaration (prototype).
    • It tells the compiler that there exists a function named sayHello that takes no parameters (void) and returns nothing (void).
  2. Function Definition:
    • Below the main() function, we define the sayHello() function.
    • The function is defined with the return type void (meaning it doesn’t return any value).
    • Inside the function body, we have the code that prints “Hello, world!” to the standard output (std::cout).

When you run the program, the main() function calls sayHello(), which in turn executes the code within its body.

You can create functions with parameters and return values as well, depending on the requirements of your program. Functions allow you to modularize your code and make it more organized and readable.

How to Call a Function ?

To call a function, write the function’s name followed by two parentheses () and a semicolon ;

When you declare a function in C++, it means you’re telling the compiler about the existence of that function and how it should be used. However, the actual execution of the function’s code occurs only when the function is called in the program.

Example:

#include <iostream>
using namespace std;

void sayHello() {
  cout << "How are you ?";
}

int main() {
  sayHello();
  return 0;
}

Ouput:

How are you ?

A function can be call multiple times:

Example:

#include <iostream>
using namespace std;

void myFunction() {
  cout << "How are you?\n";
}

int main() {
  myFunction();
  myFunction();
  myFunction();
  return 0;
}

Output:

How are you?
How are you?
How are you?

    Leave a Reply

    Your email address will not be published.

    Need Help?