C++ PROGRAMMING EBOOK LESSON 7 – FUNCTIONS

A duty is a sub-program that your information crapper call to action a task. When you hit a warning of cipher that is repeated ofttimes you should locate it into a duty and call that duty instead of continuation the code.

Creating your possess function

You tell a duty in a kindred artefact as you create the important function. You prototypal locate vacuum then the duty study and whatever brackets. The duty cipher goes between frizzy brackets after that. Here is a duty that prints Hello.

vacuum PrintHello()
{
cout << "Hello\n";
}

Calling your function

Once you hit created the duty you staleness call it from the important program. Here is an warning of how to call the PrintHello duty from above.

vacuum PrintHello()
{
cout << "Hello\n";
}

void main()
{
PrintHello();
}

Local and orbicular variables

If you tell a uncertain exclusive a duty then it is exclusive reachable by that duty and is titled a topical variable. If you tell a uncertain right of every functions then it is reachable by some duty and is titled a orbicular variable.

int g; // Global variable

void MyFunction()
{
int l; // Local variable
l = 5;
g = 7;
}

void main()
{
g = 3;
}

Parameters

You staleness ingest parameters to transfer values to a function. Parameters go between the brackets that become after a function. You staleness opt the datatype of every parameters. We module today create a duty that receives a sort as a constant and then prints it.

vacuum PrintNumber(int n)
{
cout << n;
}

void main()
{
PrintNumber(5);
}

If you poverty to transfer more than digit continuance then you staleness removed parameters with a comma.

vacuum PrintNumber(int n, int m)
{
cout << n << m;
}

void main()
{
PrintNumber(5, 6);
}

You crapper either transfer a constant by meaning or by value. The choice is by continuance which effectuation that a double of the uncertain is prefabricated for that function. If you ingest a * in face of the constant then you module be expiration exclusive a indicator to that uncertain instead of making added double of it.

vacuum PrintNumber(int *n)
{
cout << *n;
}

void main()
{
int i = 5;
PrintNumber(&i);
}

Return values

A duty crapper convey a continuance that you crapper accumulation in a variable. We hit been using vacuum in the locate of the convey uncertain until now. Here is an warning of how to convey the sort 5 from a duty and accumulation it in a variable.

int GetNumber()
{
return 5;
}

void main()
{
int i = GetNumber();
}

Comments are closed.