C++ Functions

A function is a block of code that performs a specific task.

Suppose we need to create a program to create a circle and color it. We can create two functions to solve this problem:

  • a function to draw the circle
  • a function to color the circle

Dividing a complex problem into smaller chunks makes our program easy to understand and reusable.

There are two types of function:

  1. Standard Library Functions: Predefined in C++
  2. User-defined Function: Created by users

In this tutorial, we will focus mostly on user-defined functions.


C++ User-defined Function

C++ allows the programmer to define their own function.

A user-defined function groups code to perform a specific task and that group of code is given a name (identifier).

When the function is invoked from any part of the program, it all executes the codes defined in the body of the function.


C++ Function Declaration

The syntax to declare a function is:

returnType functionName (parameter1, parameter2,...) {
    // function body   
}

Here's an example of a function declaration.

// function declaration
void greet() {
    cout << "Hello World";
}

Here,

  • the name of the function is greet()
  • the return type of the function is void
  • the empty parentheses mean it doesn't have any parameters
  • the function body is written inside {}

Note: We will learn about returnType and parameters later in this tutorial.


Calling a Function

In the above program, we have declared a function named greet(). To use the greet() function, we need to call it.

Here's how we can call the above greet() function.

int main() {
     
    // calling a function   
    greet(); 

}
Working of C++ function
How Function works in C++

Example 1: Display a Text

#include <iostream>
using namespace std;

// declaring a function
void greet() {
    cout << "Hello there!";
}

int main() {

    // calling the function
    greet();

    return 0;
}

Output

Hello there!

Function Parameters

As mentioned above, a function can be declared with parameters (arguments). A parameter is a value that is passed when declaring a function.

For example, let us consider the function below:

void printNum(int num) {
    cout << num;
}

Here, the int variable num is the function parameter.

We pass a value to the function parameter while calling the function.

int main() {
    int n = 7;
    
    // calling the function
    // n is passed to the function as argument
    printNum(n);
    
    return 0;
}

Example 2: Function with Parameters

// program to print a text

#include <iostream>
using namespace std;

// display a number
void displayNum(int n1, float n2) {
    cout << "The int number is " << n1;
    cout << "The double number is " << n2;
}

int main() {
     
     int num1 = 5;
     double num2 = 5.5;

    // calling the function
    displayNum(num1, num2);

    return 0;
}

Output

The int number is 5
The double number is 5.5

In the above program, we have used a function that has one int parameter and one double parameter.

We then pass num1 and num2 as arguments. These values are stored by the function parameters n1 and n2 respectively.

C++ function with parameters
C++ function with parameters

Note: The type of the arguments passed while calling the function must match with the corresponding parameters defined in the function declaration.


Return Statement

In the above programs, we have used void in the function declaration. For example,

void displayNumber() {
    // code
}

This means the function is not returning any value.

It's also possible to return a value from a function. For this, we need to specify the returnType of the function during function declaration.

Then, the return statement can be used to return a value from a function.

For example,

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

Here, we have the data type int instead of void. This means that the function returns an int value.

The code return (a + b); returns the sum of the two parameters as the function value.

The return statement denotes that the function has ended. Any code after return inside the function is not executed.


Example 3: Add Two Numbers

// program to add two numbers using a function

#include <iostream>

using namespace std;

// declaring a function
int add(int a, int b) {
    return (a + b);
}

int main() {

    int sum;
    
    // calling the function and storing
    // the returned value in sum
    sum = add(100, 78);

    cout << "100 + 78 = " << sum << endl;

    return 0;
}

Output

100 + 78 = 178

In the above program, the add() function is used to find the sum of two numbers.

We pass two int literals 100 and 78 while calling the function.

We store the returned value of the function in the variable sum, and then we print it.

Working of C++ Function with return statement
Working of C++ Function with return statement

Notice that sum is a variable of int type. This is because the return value of add() is of int type.


Function Prototype

In C++, the code of function declaration should be before the function call. However, if we want to define a function after the function call, we need to use the function prototype. For example,

// function prototype
void add(int, int);

int main() {
    // calling the function before declaration.
    add(5, 3);
    return 0;
}

// function definition
void add(int a, int b) {
    cout << (a + b);
}

In the above code, the function prototype is:

void add(int, int);

This provides the compiler with information about the function name and its parameters. That's why we can use the code to call a function before the function has been defined.

The syntax of a function prototype is:

returnType functionName(dataType1, dataType2, ...);

Example 4: C++ Function Prototype

// using function definition after main() function
// function prototype is declared before main()

#include <iostream>

using namespace std;

// function prototype
int add(int, int);

int main() {
    int sum;

    // calling the function and storing
    // the returned value in sum
    sum = add(100, 78);

    cout << "100 + 78 = " << sum << endl;

    return 0;
}

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

Output

100 + 78 = 178

The above program is nearly identical to Example 3. The only difference is that here, the function is defined after the function call.

That's why we have used a function prototype in this example.


Benefits of Using User-Defined Functions

  • Functions make the code reusable. We can declare them once and use them multiple times.
  • Functions make the program easier as each small task is divided into a function.
  • Functions increase readability.

C++ Library Functions

Library functions are the built-in functions in C++ programming.

Programmers can use library functions by invoking the functions directly; they don't need to write the functions themselves.

Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.

In order to use library functions, we usually need to include the header file in which these library functions are defined.

For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include the header file cmath.


Example 5: C++ Program to Find the Square Root of a Number

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double number, squareRoot;
    
    number = 25.0;

    // sqrt() is a library function to calculate the square root
    squareRoot = sqrt(number);

    cout << "Square root of " << number << " = " << squareRoot;

    return 0;
}

Output

Square root of 25 = 5

In this program, the sqrt() library function is used to calculate the square root of a number.

The function declaration of sqrt() is defined in the cmath header file. That's why we need to use the code #include <cmath> to use the sqrt() function.


Also Read:

  • C++ Standard Library functions.
  • C++ User-defined Function Types

Table of Contents

Previous Tutorial:
C++ Ternary Operator
Next Tutorial:
C++ Programming Default Arguments
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges

玻璃钢生产厂家钦州玻璃钢卡通雕塑玻璃钢雕塑厂家报价小品系列玻璃钢雕塑多少钱广东商业商场美陈市场价玻璃钢漫画人物雕塑珠海玻璃钢雕塑生产厂家南通商场新年美陈福建景区玻璃钢雕塑生产厂家上海玻璃钢雕塑的特点乐山佛像玻璃钢雕塑大型玻璃钢雕塑报价湖南商场美陈和道具玻璃钢卡通动漫雕塑修复商场美陈布置哪家好青岛玻璃钢花盆市场报价玻璃钢景观雕塑厂家直供深圳常用商场美陈销售公司广东玻璃钢卡通雕塑直销价格上海商场圣诞美陈上海玻璃钢贺平雕塑厂商场主题创意商业美陈经验浙江大型玻璃钢雕塑供应商富阳区玻璃钢金属雕塑方案雕塑玻璃钢翻制烤漆菏泽室外玻璃钢彩绘雕塑公司商场专厅的美陈布置潮州玻璃钢不锈钢雕塑南京设计玻璃钢雕塑山西省玻璃钢雕塑找哪家广东常见玻璃钢花盆香港通过《维护国家安全条例》两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”19岁小伙救下5人后溺亡 多方发声单亲妈妈陷入热恋 14岁儿子报警汪小菲曝离婚始末遭遇山火的松茸之乡雅江山火三名扑火人员牺牲系谣言何赛飞追着代拍打萧美琴窜访捷克 外交部回应卫健委通报少年有偿捐血浆16次猝死手机成瘾是影响睡眠质量重要因素高校汽车撞人致3死16伤 司机系学生315晚会后胖东来又人满为患了小米汽车超级工厂正式揭幕中国拥有亿元资产的家庭达13.3万户周杰伦一审败诉网易男孩8年未见母亲被告知被遗忘许家印被限制高消费饲养员用铁锨驱打大熊猫被辞退男子被猫抓伤后确诊“猫抓病”特朗普无法缴纳4.54亿美元罚金倪萍分享减重40斤方法联合利华开始重组张家界的山上“长”满了韩国人?张立群任西安交通大学校长杨倩无缘巴黎奥运“重生之我在北大当嫡校长”黑马情侣提车了专访95后高颜值猪保姆考生莫言也上北大硕士复试名单了网友洛杉矶偶遇贾玲专家建议不必谈骨泥色变沉迷短剧的人就像掉进了杀猪盘奥巴马现身唐宁街 黑色着装引猜测七年后宇文玥被薅头发捞上岸事业单位女子向同事水杯投不明物质凯特王妃现身!外出购物视频曝光河南驻马店通报西平中学跳楼事件王树国卸任西安交大校长 师生送别恒大被罚41.75亿到底怎么缴男子被流浪猫绊倒 投喂者赔24万房客欠租失踪 房东直发愁西双版纳热带植物园回应蜉蝣大爆发钱人豪晒法院裁定实锤抄袭外国人感慨凌晨的中国很安全胖东来员工每周单休无小长假白宫:哈马斯三号人物被杀测试车高速逃费 小米:已补缴老人退休金被冒领16年 金额超20万

玻璃钢生产厂家 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化