Beginners Guide to C++ Programming - Part 3

Functions

Beginners Guide to C++ Programming – Part 3
Functions


In the last part of this tutorial we discussed what a variable is, how it works and how to use them. I left you off with a small code snippet that is the basis for all beginners. However, before we get into the nitty gritty of dissecting the code line by line, I am
 going to go over an organizational tool, comments.

A comment, in C++, is a line or more of text that the compiler ignores. It helps you to ‘take notes’ and keep your code organized. If you have a lot of code and take longs breaks from coding, comments can help you remember what you were thinking when you wrote the code. As of now, there are two different ways to write a comment. The first way is a single line comment and the other can be as many lines as you want.

Let us start off by talking about the one line comments. Writing a comment is as easy as simply typing two forward slashes, //. Everything after the forward slashes and until the next line will not be compiled when you execute the program.

The next way to write a comment is to start by using /* and ending the comment with */. Everything between those two characters will not be compiled when the program is run. You will also notice that the text for comments is a different color, usually light green. This is even further there to help you recognize that it is a comment. As we discuss and go over how functions work and what they are made of, we will be using comments so you can get a better idea of how they work.

Functions
All C++ programs are basically a series of functions that are executed to produce some kind of output. If you remember the snippet of code I used to introduce you to your first program then you will have already seen a function. But, just as a recap I will show it to you again.

1: #include <iostream>
2: using namespace std;
3: int main()
4: {
5: cout <<”Hello World”;
6: return 0;
7: }

Starting from line 3 and ending on line 7 is the basics for all functions. Let’s dissect this program line by line.

Related information
  • Functions cut down on the amount of code you have to write.
  • Comments can help organize your code.
  • Functions should be named for what they do.