Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Type of Functions | Introduction to Functions
C++ Introduction
course content

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Variables and Data Types
3. Introduction to Operators
4. Introduction to Program Flow
5. Introduction to Functions

bookType of Functions

When creating a function, the data type it returns always specified.

In the example of the main function, we see that it has an integer data type, which means that after it finishes its work, it will return an integer value, in our case, the number 0.

Note

Since the main function is reserved in C++, it will always return integer.

But our functions can return any value:

To call a function, you need to write its name with brackets:

cpp

main

copy
1234567891011
#include <iostream> double notMainFunc() { return 3.14; } int main() { std::cout << notMainFunc(); }

We have created a function that returns a value of 3.14 as a double data type, and we have called this function to display its output on the screen.

Functions can also be string type:

cpp

main

copy
123456789101112
#include <iostream> #include <string> std::string notMainFunc() //string function { return "codefinity"; } int main() { std::cout << notMainFunc(); //calling string function }

The typedef is also applicable:

cpp

main

copy
12345678910111213
#include <iostream> typedef int MY_NEW_TYPE; MY_NEW_TYPE TYPEfunc() //MY_NEW_TYPE function { return 777; } int main() { std::cout << "New type func returned " << TYPEfunc() << std::endl; }

If you can't exactly specify the return type, the auto operator will force the compiler to do it for you:

cpp

main

copy
1234567891011121314151617
#include <iostream> auto autoFunc1() // first auto-type function { return 777; } auto autoFunc2() // second auto-type function { return 123.412; } int main() { std::cout << "First auto-type function returned " << autoFunc1() << std::endl; std::cout << "Second auto-type function returned " << autoFunc2() << std::endl; }

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 2
some-alt