To get a better understanding of how the code works, we will first implement the complete program and afterwards we will go through it step by step. To run the code, go to Debug → Start debugging/Start Without Debugging. Code Block |
---|
language | cpp |
---|
title | Hello World |
---|
| #include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
} |
![](/wiki/download/attachments/176850611/image2019-11-9_21-53-30.png?version=1&modificationDate=1573332809000&api=v2)
Alright, time to take a deeper look at the code. The first line is Code Block |
---|
| #include <iostream> |
In C++, much like in Python, we have to include libraries (headers) to perform certian actions, e.g. writing to file or solving math equations. iostream is the standard input/output streams library that enables us to print to screen (or e.g. a file). Code Block |
---|
| using namespace std; |
In this example we have chosen to include the line above to make getting into C++ easier. What using namespace std does is to silently insert std:: (std = standard) as a prefix to a lot of our standard functions. In the example above, cout will therefore be interpreted as std::cout. The short answer to why this is necessary is to specifiy where (which library) the function comes from in the case we have multiple functions with the same name. An analogy to this is how two students with the same name "Tom" are differentiated by adding e.g. the first letter of their last name; "Tom H." and "Tom B.". By specifying the standard namespace for our entire program, we will avoid having to write std:: before many of our functions, which is benefitial when first learning C++. However, note that this shortcut comes with a cost. To learn more about these negatives, read this post on Stack Overflow explaining why it is considered a bad practice. Code Block |
---|
language | cpp |
---|
title | Hello World, but without using namespace std; |
---|
| #include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
} |
Next up is Code Block |
---|
| int main() {
...
return 0
} |
What you see above is an example of a function in C++ (functions will be further covered later). The special thing about the main function is that in C++, a program shall contain a global function named main, which is the designated start of the program (the only function called when running). This is very different from both Python and MATLAB, where programs can be written without using any functions at all. To us, it means that every action we want to execute has to be described from within the main function, although you're of course allowed to call on other functions. Code Block |
---|
language | cpp |
---|
title | Hello World, not using main function -> Error |
---|
| #include <iostream>
using namespace std;
cout << "Hello World!";
// Lines starting with "//" is a comment
// This code will result in an error when trying to build. |
|