Last Updated:

C++. Function templates. Local and global variables

A template is a special kind of function. By using a function template, you can define an algorithm that will be applied to different types of data. The mechanism of the template is that at compile time, a specific data type is passed to the function as a parameter.

The simplest template function in general form can be written as follows:

template <class Type> header
{
function body

}

Typically, angle brackets indicate the data types used in the function. Each type begins with the service word class. In general, a list can contain not only data types, but also variable names.

Consider an example of a pattern for finding the smallest of four numbers.

This is the result of the program:

Similar programs are better and more convenient to compile using arrays. We will talk about them in the following lessons. In the meantime, let's take a closer look at the local and global variables that have already been mentioned in the first lesson about functions.

As you know, at the place of declaration, variables in the C++ language are divided into three classes: local, global and variables described in the list of formal parameters of the function. All of these variables have different scopes.

Local variables are declared inside a function and are available only in the function. Such variables are said to have local visibility, that is, they can only be used in the function in which they are described.

Global variables are described outside of all functions. They are accessible from any point in the program, that is, their scope covers the entire code.

The same name can be used when defining a global variable and a local variable. In this case, in the body of the function, the local variable has an advantage and "closes" the global variable. Outside of this function, the global description of the variable "works".

From a function that has a local description of a variable, you can access a global variable with the same name by using a scope extender operator.

Let's look at an example:

The result of the program:

This was the last lesson in the C++ Functions category. In the following lessons, you will learn what arrays are and how to use them in the program's algorithm.