Let’s get right into it. Open Visual Studio (VS), click on New Project… under Start; click Visual C++; Select Empty Project; give the project the name “hello-world” (or whatever); and then click okay. This will build a new project.
Once the project is created, under Solution Explorer (right hand pane), right-click Source Files; Add > New Item…; select Visual C++; C++ File (.cpp); give the file a name (in this case main.cpp or whatever); and click Add. Now you have a new source code file.
Type the following code into your new file.
|
1 2 3 4 5 6 7 8 |
#include <iostream> using namespace std; int main () { cout << "Hello world!"; system( "pause>nul" ); return 0; } |
Now it is time to compile the source code.
Clicking on the Local Windows Debugger will compile and execute the source code and you should be left with the following window.
Now let’s break down the code line by line.
|
1 2 3 4 5 6 7 8 |
#include <iostream> using namespace std; int main () { cout << "Hello world!"; system( "pause>nul" ); return 0; } |
Line one, #include <iostream>, is called a preprocessor directive. This tells the compiler that an external library needs to be included at compile time. The preprocessor inserts the contents of the file iostream (which is used for input and output functions). This ensure that output functions and operators, like cout, will work.
Line two, using namespace std;, is an advanced topic, so we will just introduce the idea here. This allows us to use function from the namespace std without prepending them with a namespace identifier. Basically this makes it so we can display text with cout rather than std::cout. I’ll leave it at that for now.
|
1 2 3 4 5 6 7 8 |
#include <iostream> using namespace std; int main () { cout << "Hello world!"; system( "pause>nul" ); return 0; } |
Line four is the declaration statement of the main function. A function, which we’ll get into in a later lesson, can be thought of as a wrapper for a collection of instructions/statements. In C++ when source code is compiled the starting point of the program is indicated by the main function. Every C++ program should have one main function. The instructions wrapped in a function are also wrapped with curly braces { and }.
int refers to the type of data that is expected to be returned by the function. In this case int is short for integer. So the function is expected to return an integer value back to the operating system on completion of execution.
|
1 2 3 4 5 6 7 8 |
#include <iostream> using namespace std; int main () { cout << "Hello world!"; system( "pause>nul" ); return 0; } |
Line five is responsible for printing the words “Hello world!” to the console screen (the black screen with white text). cout is an object (objects will be covered in a later lesson) that is part of the standard output stream class (classes will be covered in a later lesson as well). cout sends the string of characters (often referred to as a string) following the stream insertion operator (<<) to the console (cout is short for console output). This and operators will be covered more later.
cout is the reason we need to include the iostream external library. Without iostream included, cout does not work because it is not available.
|
1 2 3 4 5 6 7 8 |
#include <iostream> using namespace std; int main () { cout << "Hello world!"; system( "pause>nul" ); return 0; } |
Line six is a call to a function built into C++. The system function is used to execute commands that are available in the system running below our application (generally an operating system and Windows in this instance). The use of this function here is mostly for convenience since executing this code without displays “Hello world!” to the console and promptly closes the window. The command “pause>nul” causes the operating system to pause execution of the program until some kind of keyboard input is detected, then it will continue executing the program.
“pause>nul” is a DOS command for pausing execution without displaying the default prompt of “Press any key to continue…” that is displayed with just system( “pause” ).
|
1 2 3 4 5 6 7 8 |
#include <iostream> using namespace std; int main () { cout << "Hello world!"; system( "pause>nul" ); return 0; } |
The last line in the function, line seven, is pretty simple. It returns an integer back to the system/function that called the function (in this case it was Windows that called this program). Since the function main is expected to return an int value back to the OS, we return the value of 0. There will be more on returning values later.
I know the “Hello world” program can be a bit underwhelming. It’s simple and does very little, but it gives a very good foundation to start building on. There is a lot C++ can do, but understanding this most basic of programs, the rest will fall into place.
Now that you have some of the basics of programming down, it’s time to dig in and start to understand the basics of the language. The following six sections break down C++’s lexical structure (the letters, symbols, and words that make up the language).
A token is the most basic element of any programming language. Tokens fall into five categories identifiers, reserved words, operators, literals, and punctuators.
An identifier is simply a name. Identifiers are used to name variables, functions, objects, classes, structures, arrays, and more.
Identifiers must follow specific rules in order to be considered valid by the compiler.
|
1 2 3 4 5 |
a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 _ |
|
1 |
0 1 2 3 4 5 6 7 8 9 |
C++ has reserved words for use by the language often referred to as reserved words or keywords. You cannot use the following words as identifiers. If you do you will most likely encounter errors
| and | and_eq | asm |
| auto | bitand | bitor |
| bool | break | case |
| catch | char | class |
| compl | const | const_cast |
| continue | default | delete |
| do | double | dynamic_cast |
| else | enum | explicit |
| export | extern | false |
| float | for | friend |
| goto | if | inline |
| int | long | mutable |
| namespace | new | not |
| not_eq | operator | or |
| or_eq | private | protected |
| public | register | reinterpret_cast |
| return | short | signed |
| sizeof | static | static_cast |
| struct | switch | template |
| this | throw | true |
| try | typedef | typeid |
| typename | union | unsigned |
| using | virtual | void |
| volatile | wchar_t | while |
| xor | xor_eq |
Table 0.1—C++ Reserved Words
Visual Studio has added more reserved words to this list.
| __abstract | __alignof | __asm |
| __assume | __based | __box |
| __cdecl | __declspec | __delegate |
| __event | __except | __fastcall |
| __finally | __forceinline | __gc |
| __hook | __identifier | __if_exists |
| __if_not_exists | __inline | __int16 |
| __int32 | __int64 | __int8 |
| __interface | __leave | __m128 |
| __m128d | __m128i | __m64 |
| __multiple_inheritance | __nogc | __noop |
| __pin | __property | __raise |
| __sealed | __single_inheritance | __stdcall |
| __super | __try/__except | __try/__finally |
| __try_cast | __unaligned | __unhook |
| __uuidof | __value | __virtual_inheritance |
| __w64 | __wchar_t | abstract |
| alignas | alignof | array |
| char16_t | char32_t | constexpr |
| decltype | delegate | deprecated |
| dllexport | dllimport | event |
| final | finally | friend_as |
| gcnew | generic | in |
| initonly | interface class | interface struct |
| interior_ptr | literal | naked |
| noexcept | noinline | noreturn |
| nothrow | novtable | nullptr |
| override | property | ref class |
| ref struct | safecast | sealed |
| selectany | static_assert | thread |
| thread_local | using declaration | using directive |
| uuid | value class | value struct |
Table 0.2—Visual Studio Reserved Words
Operators are used to manipulate data. The best example of operators are arithmetic operators such as addition (+), subtraction (-), multiplication (×), and division (÷). The topic of operators is actually quite vast and will therefore receive it’s own lesson, but we’ll cover some of the basics here.
If you’ve done any math in your life you should be able to figure out how these work pretty quickly. There are five (yes, five) basic arithmetic operators addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). Modulus is the one that most people are unfamiliar with but the operation lends itself quite nicely to many programming applications. Here is a basic breakdown of the math operators.
| Operator | Definition | Example |
| + | Addition | 1 + 2 = 3 |
| - | Subtraction | 13 – 8 = 5 |
| * | Multiplication | 13.50 * 1.06 = 14.31 |
| / | Division | 100 / 5 = 20 |
| % | Modulus | 9 % 2 = 1 |
Table 0.3—Arithmetic Operators
Let’s take a moment to look at the modulus operator, since that should be the only operator you may be unfamiliar with. Modulus returns the remainder of division. In the example above
|
1 2 3 4 |
1) 9 % 2 = ? 2) 9 / 2 = 4.5 3) Remainder = 0.5 4) 0.5 * 2 = 1 |
Or if you do it the way I learned in first or second grade (when they didn’t quite want to introduce fractions
The modulus is the remainder value of 1.
Literals, or constants, are values that appear directly in a program and do not change value during execution. There are four categories of literals used in C++, integers, floating-point, character, and character-strings.
| Literal Example | Type | Notes |
| 5 | Integer | |
| 255 | Integer | |
| 0x8F | Integer | 143 in hexadecimal notation; Hex integers start with “0x” |
| 0452 | Integer | 298 in octal notation; Octal integers start with “0″ |
| 3.14 | Floating | Notice the decimal |
| 5.0 | Floating | Again with the decimal |
| 6.022e23 | Floating | Expressed in scientific notation |
| ‘a’ | Character | Must be surrounded by single quotes. |
| “A lame comment about C++!” | String | Surrounded by double quotes |
At this point the purpose of literals may be vague, but in the next lesson, we will cover what they are used for and put them to good use.
With a word like punctuators C++ really starts to sound like a written language. Punctuators help with compilation of code. Just like punctuation in any written language, the symbols help the reader understand the meaning of what is written. Punctuators in C++ do the same thing, they tell the compiler what the coder actually meant as well as giving additional meaning to blocks of code.
The punctuation marks in C++ are
|
1 2 |
; , . ' " < > ( ) { } [ ] # : / \ ! % ^ & * - + = | ~ ? |
The top line of punctuators are more common than the bottom and punctuators [ ], ( ), and { } always appear in pairs. Most C++ instructions end with a ; (We will discuss exceptions to that rule throughout these lessons).
When looking at the source code of our first program the formatting, line numbers, syntax highlighting, and structure helps us to understand what the code is doing.
|
1 2 3 4 5 6 7 8 |
#include <iostream> using namespace std; int main () { cout << "Hello world!"; system( "pause>nul" ); return 0; } |
However, the compiler sees our code as this
#include<iostream>using namespace std;int main(){cout<<"Hello world!";system("pause>nul");return 0;}
Without the punctuators, the compiler would have a hard time clearly translating the developer’s intention into executable code.
Comments are segments of text within source code that are ignored by the compiler. This may seem useless at first, but comments are beneficial for developers.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
/* Our first program. This program is awesome. Or at least it should lead to some much better programs. */ #include <iostream> using namespace std; // Use the std namespace int main () { cout << "Hello world!"; // Display "Hello world!" system( "pause>nul" ); // Pause execution without prompt return 0; // Return 0 to the OS } |
Comments (in orange) come in two varieties block and inline. Block comments usually span several lines, but can be all on one line, and begin with /* and end with */. Everything between /* and */ is ignored by the compiler. Inline comments begin with //. Everything following // to the end of the line is ignored by the compiler.