A to Z to get you started with C++ in one post. This post covers the basics, and covers many practical examples in C++.
If you've done C or Java before, this should be a breeze. But even if you haven't, don't worry! After reading this blog post, you'll have the hang of C++ Basics. If you're looking for a more in depth understanding, you can read my post on C++ concepts here.
First off, a C++ program has a structure. First, we have definitions and prototypes (more on this later)
Then we have the main block, and user functions.
A basic program that prints "Hello, World!" to the console looks like this:
1 #include <iostream>
2 using namespace std;
3
4 int main(){
5 cout << "Hello World!\\n";
6 return 0;
7 }
If you thought, "That looks extremely complicated for Hello World code", you're absolutely right.
But once we break it down into chunks, it's not so bad.
Lines 1 is header file and Line 2 is a declaration. These lines just tell the compiler which "libraries" are used.
Then, the main block is where the main code to be executed goes. That's where we print to the console using the cout statement.
Finally, we end the program with return 0, which indicates that the program finished successfully.
If you don't fully understand, don't fret. You'll get used to the layout in a bit.
For now, some Important Points to note:
The top of the program starts with header files and declarations: Line 1 is the header file library and Line 2 is the namespace declaration that tells us we can name our objects/variables from the standard library. If you omit this line, you will need to append a prefix of std:: infront of certain objects, eg. cout in line 5. cout is covered in more detail later, but for now we will focus on whether we need to add a prefix to it.
cout in Line 5: Usage in the program comparison with and without namespace declaration: