Overblog
Edit post Follow this blog Administration + Create my blog
Learn to Code with KC

Functions

The next concept I will write about is the function. Functions are also highly important for effective programs. You only have to write what the function does once. After you tell the computer what the function does all you have to do is call the function. To call the function you use void and add parentheses at the end. You use brackets with functions. You put everything else within the brackets.

#include <iostream>

using namespace std;

void print_giraffe()

{

cout << "Giraffe" << endl;

}

int main()

{

print_giraffe();

return 0;

}

Giraffe

Functions can perform many tasks. I will mention some of things they can do now and will introduce others later.

It is possible to add variables to a function. You still declare the variables before using them.

#include <iostream>

using namespace std;

int i;

void number()

{

i = 3;

cout << i << endl;

}

int main()

{

number();

}

3

If you want to you can put i = 3 in the main function before calling the number function you can. It will work the same way as the first program.

#include <iostream>

using namespace std;

int i;

void number()

{

cout << i << endl;

}

int main()

{

i = 3;

number();

}

3

You do not have to write the contents of the function immediately. Sometime you would rather declare the function and write its contents later on. After you write what the function does you can use it at any time unless the function is within brackets and you are trying to use it outside the brackets.

#include <iostream>

using namespace std;

int i;

void number();

int j;

void number()

{

i = 3;

j = 2;

cout << "i is equal to: " << i << endl;

cout << "j is equal to: " << j << endl;

}

int main()

{

number();

}

i is equal to: 3

j is equal to: 2

The values of the variable inside the made up function are kept when using the function in the main function. The variables no longer have value outside the function.

Share this post
Repost0
To be informed of the latest articles, subscribe:
Comment on this post
C
This article is very nice as well as very informative. I have known very important things over here. I want to thank you for this informative read.
Reply