• Home
  • 6.1 Function Basics

6.1 Function Basics

View Categories

6.1 Function Basics

< 1 min read

Table of Contents

A function is a named block of code that performs a specific operation. Functions allow a program to divide a larger task into smaller, reusable units and avoid repeating the same code.

A function can be called from different locations within a program. Depending on its definition, a function can accept input through parameters and return a value to the caller.

Source Code #

#include <iostream>

void greet()
{
    std::cout << "Hello from the function.\n";
}

int main()
{
    greet();

    return 0;
}

Output #

Hello from the function.

Explanation #

  • void greet() defines a function named greet.
  • void specifies that the function does not return a value.
  • The statements enclosed within {} form the function body.
  • std::cout inside the function displays the message when the function is executed.
  • greet(); calls the function from main().
  • When the function is called, program execution transfers to the function body.
  • After the function finishes executing, control returns to the statement following the function call.
  • A function can be called multiple times from different locations in a program.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *