“I don’t like to look typical” Adam Lambert
Before we get into the nitty gritty details of the C++ syntax and structure, we need to have a general sense of how a C++ source code looks like and how it works. For this reason, this section will be about a shallow explanation of syntax and structure about a simple C++ source code.
Let’s take a look at this example:
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World!";
return 0;
}
If we compile and run the code above, we will get the message “Hello World!” on the monitor.
Alright let’s start with the first line of this code:
#include <iostream>
The keyword #include is a preprocessor directive. We use this directive to include files that our program depends on them. For example the cout in our program is an object and its resource (class in this case) is in another file. So our program is dependent on an external file (iostream) and in order to have a successful execution, we need to import that file.
Preprocessor is actually a program that will run before the compiler starts to compile a source code. The main job of a preprocessor is to check the target source code, look for directives that it knows how to implement them (#include is one of them) and actually implement them.
Directives:
Directives are a set of instructions if you will, that needs to be done at preprocessor time and before the compiler start to compile the target source code.
Take the `#include` directive for example. The job of this directive is to declare the address of an external resource (file) and when the preprocessor runs, one of its jobs is to find the file and bring its content to the target source code.
Why we do that? Remember when we used the cout object in the source code? Well, we mentioned that the resource of this object should be present in the source code when the program is running; it turns out the resource is in a file named iostream. When we called the #include directive, we ordered the preprocessor to include the content of the iostream file into our source code. So with the help of this directive now we have the content we need for the cout object.
Note: there are many more directives in C++ which they come from the C language. You can learn more about them in preprocessor and directives section of the C language.
The next line of this source code is ` using namespace std;`
The call to using namespace std statement is actually a directive.
Both using and namespace are C++ keywords but the std is a name of a namespace (for now think of it as an area within a file).
Within this area, there is an object named cout that we need it in order to send data to output stream (the monitor for example).
So when we used using namespace std, we told the compiler that we want to have the accessibility to the content of this std area because we’re going to use the cout objet.
Note: this topic is about namespaces and you can learn about them in its section.
Functions and the `main()` function:
Consider a company that produces mobile phone. The goal of the company is to sale mobile phone to people as many as it possibly can.
But this company in order to reach its goal, divided the works that should be done and apply them to different departments in the company.
One department is marketing and the people there are focused on finding new markets and ways to sell to more people.
Another department is R&D and the people there are focused on increasing the quality of their product.
And a couple of other departments that are focused on other part of the works involved.
As you can see by forming different departments and allowing each department focus on part of the tasks the entire process becomes more manageable.
Functions in C++ programming somehow act like different departments in a company.
A program usually has a goal, for example considering a calculator; its main goal is to take numbers as its input and do mathematical operations (adding, subtraction, division, multiplication etc.) on them.
We can consider each of these mathematical operations as a separated task and put it in different function. For example one function contains the instructions about how to multiply input values to each other; the other function contains instructions about how to divide input values; another function is in charge of getting inputs from the user and send those inputs to a function if needed etc.
As you can see, by diving the whole instructions and works of a program into functions (sub-task) and focusing on those functions separately we can increase the speed and quality of developing the application at the end.
Note: functions are the place where tasks of a program runs and so at least there should be one function present in the program otherwise there won’t be any execution.
Now that we know what function is and why we need them, let’s see the structure of a function in the C++ language:
type function-name() {
//body...
}
-
Type: A function can return a value. For example
if the job of a function is to multiply a couple of numbers together, we
can build the function in a way that will return the result of the
multiplication to the caller.
Note: functions can call each other. The function that calls another function is called caller function and the function that is called is named callee or called function.
Now because computers are very specific and exact, they need to know if a function returns a value when it finished its work, and if yes, what type the returned value is.
For example decimal numbers like 1,2,3,4,5,6 etc. are called integer and their type in C++ is called int or values like 2.3, 44.34, 533.342 etc. that have fraction part, are of float type. So if a function at the end will return a value of type int we need to replace the type with the keyword int in this structure.
Example:
int integerFunction(){
//body…
}
Also if a function does not return a value, its type should be declared void.
Example:
void noReturnValueFunction(){
//body…
}
Note: you can learn more about types in data-types section.
-
Function-name: any function needs name,
otherwise how can we call a function? You should know that C++ is
case-sensitive and as a result a name like `main` is different than a
name like `Main` or `MAIN`. Also the function name must have no spaces
in it, and it must conform to the same naming rules that C++
variables follow which is only letters, digits, and the
underscore character can be used and the first character cannot be a
digit. -
(): After the name of a function we use
parentheses and within the parentheses we can declare whether or not the
function accepts any input.
For example if a function needs at least two inputs to work correctly, we need to declare two parameter (separated via comma) within the parentheses and anywhere we want to call the function, we need to set two input value for the function as well.
Example:
int sum(int valueA , int valueB){
return valueA+ valueB;
}
This is another function named sum and it returns a value of type int. The function also has two parameters of type int (the name of the first parameter is valueA and the name of the second parameter is valueB). The job of the function is to sum two values and return the result to the caller. Now if we want to call this function we need to put two values of type int in the function (also called argument) so that the function can work properly.
-
{}: the body of a function starts from the open
brace `{` and ends with the closing brace `}`.
Within the body of a function we can define the instructions that we want to be run after calling the function.
Note: there’re more into functions and we will get into those details in functions-section.
Now that we are familiar with the overall structure of a function, let’s take a look at the example above one more time:
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World!";
return 0;
}
In this example we have a function named main. The return value of this function is of type int and within the body of this function we have two instructions which are:
cout<<"Hello World!";
return 0;
The first instruction is a call to `cout`: the `cout` is an object that is created from `ostream` class.
Consider it this way: A car before being produced is nothing but a blueprint or a technical map that shows how the car should be built and what materials should be used in the car.
Similarly, cout is an object that is built from ostream class (you can think of it as the blueprint that declare what services the cout object after being built should possess) and so the cout provides the services that are needed to send the users data to output.
For now just remember that when we want to send data to output via the call to cout, we use the << operator (which is one of the services of the cout) and put the data on the right side of this operator.
Example:
cout<<"Hello World!";
Note: the entire ` cout<<"Hello World!"; ` line is called statement. And a statement ends with semicolon `;`. If you forget to add a semicolon at the end of a statement, you'll get compile time error.
return 0;: within the body of the `main` function we have only 2 statements (instructions) and this one is the last statement. The keyword `return` is an especial C++ keyword and when we use it in a function, it means the function should terminate and return to the caller function (if any). That's why we put this statement at the end of a function (because no-other instructions after the `return` statement will run).
You should know that in front of the return keyword, we put the value that we want to be returned to the caller of the function.
Also the return statement is only used for those type of functions that return a value to their caller, otherwise if the target function does not return any value, we don’t need to use this statement.
Note: just like a door of a house that is the entry point of the house, the entry point of a program is the `main` function. Any program we build should have one `main` function otherwise the compiler won't compile the source code. Also it’s the operating system that will call the `main` function and so OS is the caller of this function and any return value from this function will be sent to the OS.
The value we put in front of the return keyword should be the same as the return-type declared for the function. For example the main function’s return type is int and so we’re only allowed to put decimal numbers in front of the return keyword. (If we use other types, the compiler will try to cast that type if it’s possible otherwise the compiler won’t compile).
Let’s see another example:
#include <iostream>
using namespace std;
int sum(int , int );
int main()
{
int result = sum(10 , 20);
cout<<result;
return 0;
}
int sum(int valueA , int valueB){
return valueA+ valueB;
}
Output: 30;
In this example we have two functions:
-
main
-
sum
The main function is the entry point of the program and so the instructions within the body of this function will run first.
Note: above the main function, there’s a line called function-prototype declaration. This is used to tell the compiler that there’s a function named sum in the source code and we might use it later in the program. Via this declaration, the compiler knows what’s the return value of the sum function, and what type of parameter it takes (if any). After that if we attempt to set a value of different type to the sum function as its input or return a value of different type, because the compiler knows about this function, it will return error and won’t compile.
The first line of the main function is to declare a variable of type int with the name result and for its value we called the sum function with two values as its argument.
First of all, we use variables to store values in memory. Via a variable name we can access the value that is stored in its memory. Also any variable has type and that will declare how much space in the memory should be set aside of the target variable. Here we created a variable of type int with the name result. This will cause a memory location be set aside for this variable and any value we assign to it will be stored in that memory location.
Next, in order to assign a value to this variable, we use the = symbol (AKA assign symbol). And on the right side of the assign = symbol, we put the value for the target variable which should be on the left-side of the assign = symbol. In this example the assigned value is the result and retuned value of calling the sum function.
In order to call a function, we use the name of that function + parentheses and within the parentheses we put any argument that the target function needs. For example the sum() function needs two arguments of type int.
Note: each argument is separated by comma `,`;
After calling the sum() function, the body of this function will run. Within the body of sum() we can see the two arguments are added together and the result is returned to the caller function.
Note: the valueA and valueB are variable as well. This means a memory location is set aside for each of these two variables. And when we called the sum function, the first argument was assigned to the valueA and the second argument was set for the valueB variable.
Later on, when we ran the valueA+valueB expression, behind the scene it’s the values of each of these two variables that are added together. Basically when we use a variable’s name, it’s like we’re using the value of that variable. (Variables are linked to their data, any time we access a variable, we’re accessing the value of that variable in the memory).
Note: check the variables section to learn more about variables.
Now after the sum function returned the result, this result is assigned to the result variable and in the next line within the main function we called the << operator which is a service of the cout object and on the right side of this operator we put the name of the result variable. This will cause the value stored in this variable to be sent to the output (monitor in this case).
At the end, there’s the call to the return 0 statement, which will terminate the main function and returns the value 0 to the operating system.
After that the work of the program is done and it will terminate.