C++ / Functions and Scope in C++

Creating and Calling Functions in C++

In this tutorial, we will cover the process of creating and calling functions in C++. You will learn how to define a function and how to call it in your code.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores functions, parameter passing, and variable scope in C++.

1. Introduction

In this tutorial, we will learn about creating and calling functions in C++. Functions are fundamental to structured and object-oriented programming in C++. They help us divide our code into reusable parts which can help make our programs more organized, more manageable, and more efficient.

By the end of this tutorial, you will be able to define your own functions, call them in your code, and understand the basic concepts of function return types and parameters.

Prerequisites: Basic understanding of C++ programming including variables, data types, and control structures.

2. Step-by-Step Guide

A function in C++ is defined with the function name, followed by parentheses (). The code to be executed by the function is placed within curly braces {}.

A simple function definition looks like this:

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

In this case, void is the return type of the function, specifying that this function does not return a value. The myFunction() is the name of the function.

To call a function, you simply use its name followed by parentheses:

myFunction();

Function Parameters and Return Values

Functions can also take parameters, which are values you can pass into the function when you call it. Parameters are specified in the parentheses when you define the function.

void sayHelloTo(string name) {
  cout << "Hello, " << name << "!\n";
}

In this case, name is a parameter of type string. When you call the function, you can pass in a string:

sayHelloTo("Alice");

This will output: Hello, Alice!

Functions can also return values using the return keyword. The return type is specified before the function name:

int add(int x, int y) {
  return x + y;
}

This function takes two integers as parameters and returns their sum.

3. Code Examples

Here's a full code example with multiple functions:

#include <iostream>
using namespace std;

// Function declaration
void greet();
int add(int a, int b);

int main() {
  greet();  // Function call

  int result = add(5, 3);  // Function call
  cout << "The sum is: " << result << "\n";  // Output: The sum is: 8

  return 0;
}

// Function definition
void greet() {
  cout << "Hello, C++ Programmer!\n";  // Output: Hello, C++ Programmer!
}

// Function definition
int add(int a, int b) {
  return a + b;
}

4. Summary

In this tutorial, we've learned how to define and call functions in C++. We've covered function return types, parameters, and how to use functions to organize our code.

Next steps for you would be to learn about more advanced topics in functions such as default arguments, function overloading, and recursion.

Additional resources:
- C++ Functions
- C++ Functions and Objects

5. Practice Exercises

  1. Write a function that takes a string as a parameter and prints it to the console.
  2. Write a function that takes two integers as parameters and returns their product.
  3. Write a function that takes an integer as a parameter and returns whether it is even or odd.

Solutions:

void printString(string str) {
  cout << str << "\n";
}
printString("Hello, world!");  // Output: Hello, world!
int multiply(int a, int b) {
  return a * b;
}
cout << multiply(3, 4);  // Output: 12
string isEvenOrOdd(int num) {
  if (num % 2 == 0) {
    return "Even";
  } else {
    return "Odd";
  }
}
cout << isEvenOrOdd(7);  // Output: Odd

Continue to practice writing functions to solve different problems. The more you practice, the more comfortable you will become with functions!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help