c++ English Tutorial part-1|Structure of a program

15
328

c++

The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called “Hello World”, which simply prints “Hello World” to your computer screen. Although it is very simple, it contains all the fundamental components C++ programs have:

1
2
3
4
5
6
7
// my first program in C++
#include <iostream>

int main()
{
  std::cout << "Hello World!";
}
Hello World!

The left panel above shows the C++ code for this program. The right panel shows the result when the program is executed by a computer. The grey numbers to the left of the panels are line numbers to make discussing programs and researching errors easier. They are not part of the program.

Let’s examine this program line by line:

Line 1: // my first program in C++
Two slash signs indicate that the rest of the line is a comment inserted by the programmer but which has no effect on the behavior of the program. Programmers use them to include short explanations or observations concerning the code or program. In this case, it is a brief introductory description of the program.

 

Line 2: #include <iostream>
Lines beginning with a hash sign (#) are directives read and interpreted by what is known as thepreprocessor. They are special lines interpreted before the compilation of the program itself begins. In this case, the directive #include <iostream>, instructs the preprocessor to include a section of standard C++ code, known as header iostream, that allows to perform standard input and output operations, such as writing the output of this program (Hello World) to the screen.

 

Line 3: A blank line.
Blank lines have no effect on a program. They simply improve readability of the code.

 

Line 4: int main ()
This line initiates the declaration of a function. Essentially, a function is a group of code statements which are given a name: in this case, this gives the name “main” to the group of code statements that follow. Functions will be discussed in detail in a later chapter, but essentially, their definition is introduced with a succession of a type (int), a name (main) and a pair of parentheses (()), optionally including parameters.

The function named main is a special function in all C++ programs; it is the function called when the program is run. The execution of all C++ programs begins with the main function, regardless of where the function is actually located within the code.

 

Lines 5 and 7: { and }
The open brace ({) at line 5 indicates the beginning of main‘s function definition, and the closing brace (}) at line 7, indicates its end. Everything between these braces is the function’s body that defines what happens when main is called. All functions use braces to indicate the beginning and end of their definitions.

 

Line 6: std::cout << "Hello World!";
This line is a C++ statement. A statement is an expression that can actually produce some effect. It is the meat of a program, specifying its actual behavior. Statements are executed in the same order that they appear within a function’s body.

This statement has three parts: First, std::cout, which identifies the standard character output device (usually, this is the computer screen). Second, the insertion operator (<<), which indicates that what follows is inserted into std::cout. Finally, a sentence within quotes (“Hello world!”), is the content inserted into the standard output.

Notice that the statement ends with a semicolon (;). This character marks the end of the statement, just as the period ends a sentence in English. All C++ statements must end with a semicolon character. One of the most common syntax errors in C++ is forgetting to end a statement with a semicolon.

You may have noticed that not all the lines of this program perform actions when the code is executed. There is a line containing a comment (beginning with //). There is a line with a directive for the preprocessor (beginning with#). There is a line that defines a function (in this case, the main function). And, finally, a line with a statements ending with a semicolon (the insertion into cout), which was within the block delimited by the braces ( { } ) of themain function.

The program has been structured in different lines and properly indented, in order to make it easier to understand for the humans reading it. But C++ does not have strict rules on indentation or on how to split instructions in different lines. For example, instead of

1
2
3
4
int main ()
{
  std::cout << " Hello World!";
}

We could have written:

 
int main () { std::cout << "Hello World!"; }

all in a single line, and this would have had exactly the same meaning as the preceding code.

In C++, the separation between statements is specified with an ending semicolon (;), with the separation into different lines not mattering at all for this purpose. Many statements can be written in a single line, or each statement can be in its own line. The division of code in different lines serves only to make it more legible and schematic for the humans that may read it, but has no effect on the actual behavior of the program.

Now, let’s add an additional statement to our first program:

1
2
3
4
5
6
7
8
// my second program in C++
#include <iostream>

int main ()
{
  std::cout << "Hello World! ";
  std::cout << "I'm a C++ program";
}
Hello World! I'm a C++ program

In this case, the program performed two insertions into std::cout in two different statements. Once again, the separation in different lines of code simply gives greater readability to the program, since main could have been perfectly valid defined in this way:

 
int main () { std::cout << " Hello World! "; std::cout << " I'm a C++ program "; }

The source code could have also been divided into more code lines instead:

1
2
3
4
5
6
7
int main ()
{
  std::cout <<
    "Hello World!";
  std::cout
    << "I'm a C++ program";
}

And the result would again have been exactly the same as in the previous examples.

Preprocessor directives (those that begin by #) are out of this general rule since they are not statements. They are lines read and processed by the preprocessor before proper compilation begins. Preprocessor directives must be specified in their own line and, because they are not statements, do not have to end with a semicolon (;).

15 COMMENTS

  1. Наша команда искусных мастеров готова предъявить вам новаторские методы, которые не только подарят надежную оборону от зимы, но и преподнесут вашему дому современный вид.
    Мы практикуем с самыми современными составами, заверяя постоянный термин использования и прекрасные результаты. Теплоизоляция облицовки – это не только экономия тепла на подогреве, но и ухаживание о окружающей среде. Экономичные подходы, какие мы внедряем, способствуют не только твоему, но и сохранению природной среды.
    Самое центральное: [url=https://ppu-prof.ru/]Утепление и обшивка дома стоимость[/url] у нас начинается всего от 1250 рублей за м²! Это доступное решение, которое преобразит ваш хаус в фактический теплый уголок с минимальными затратами.
    Наши достижения – это не исключительно утепление, это постройка области, в где все член преломляет ваш персональный манеру. Мы возьмем во внимание все твои желания, чтобы переделать ваш дом еще еще более комфортным и привлекательным.
    Подробнее на [url=https://ppu-prof.ru/]www.ppu-prof.ru[/url]
    Не откладывайте труды о своем жилище на потом! Обращайтесь к мастерам, и мы сделаем ваш корпус не только тепличным, но и более элегантным. Заинтересовались? Подробнее о наших работах вы можете узнать на интернет-портале. Добро пожаловать в мир спокойствия и уровня.

  2. Aviator Spribe играть на компьютере
    Alas! Unfortunately!
    Добро пожаловать в захватывающий мир авиаторов! Aviator – это увлекательная игра, которая позволит вам окунуться в атмосферу боевых действий на небе. Необычные графика и захватывающий сюжет сделают ваше путешествие по воздуху неповторимым.

    Выигрывайте с автоматом Aviator Spribe играть с друзьями онлайн казино в нашем казино!
    Aviator игра позволит вам почувствовать себя настоящим пилотом. Вам предстоит совершить невероятные маневры, выполнять сложные задания и сражаться с противниками. Улучшайте свой самолет, чтобы быть готовым к любым ситуациям и становиться настоящим мастером.
    Основные особенности Aviator краш игры:
    1. Реалистичная графика и физика – благодаря передовой графике и реалистичной физике вы почувствуете себя настоящим пилотом.
    2. Разнообразные режимы игры и миссии – в Aviator краш игре вы сможете выбрать различные режимы игры, такие как гонки, симулятор полетов и захватывающие воздушные бои. Кроме того, каждая миссия будет предлагать свои собственные вызовы и задачи.
    3. Улучшение и модернизация самолетов – в игре доступны различные модели самолетов, которые можно покупать и улучшать. Вы сможете устанавливать новое оборудование, улучшать двигательность и мощность своего самолета, а также выбирать различные варианты окраски и декорации.
    Aviator краш игра – это возможность испытать себя в роли авиатора и преодолеть все сложности и опасности воздушного пространства. Почувствуйте настоящую свободу и адреналин в Aviator краш игре онлайн!
    Играйте в «Авиатор» в онлайн-казино Pin-Up
    Aviator краш игра онлайн предлагает увлекательную и захватывающую игровую атмосферу, где вы становитесь настоящим авиатором и сражаетесь с самыми опасными искусственными интеллектами.
    В этой игре вы должны показать свое мастерство и смекалку, чтобы преодолеть сложности многочисленных локаций и уровней. Вам предстоит собирать бонусы, уклоняться от препятствий и сражаться с врагами, используя свои навыки пилотирования и стрельбы.
    Каждый уровень игры Aviator краш имеет свою уникальную атмосферу и задачи. Будьте готовы к неожиданностям, так как вас ждут захватывающие повороты сюжета и сложные испытания. Найдите все пути к победе и станьте настоящим героем авиатором!
    Авиатор игра является прекрасным способом провести время и испытать настоящий адреналиновый разряд. Готовы ли вы стать лучшим авиатором? Не упустите свой шанс и начните играть в Aviator краш прямо сейчас!
    Aviator – играй, сражайся, побеждай!
    Aviator Pin Up (Авиатор Пин Ап ) – игра на деньги онлайн Казахстан
    Aviator игра предлагает увлекательное и захватывающее разнообразие врагов и уровней, которые не оставят равнодушными даже самых требовательных геймеров.
    Враги в Aviator краш игре онлайн представлены в самых разных формах и размерах. Здесь вы встретите группы из маленьких и быстрых врагов, а также огромных боссов с мощным вооружением. Разнообразие врагов позволяет игрокам использовать разные тактики и стратегии для победы.
    Кроме того, Aviator игра предлагает разнообразие уровней сложности. Выберите легкий уровень, чтобы насладиться игровым процессом, или вызовите себе настоящий вызов, выбрав экспертный уровень. Независимо от выбранного уровня сложности, вы получите максимум удовольствия от игры и окунетесь в захватывающий мир авиаторов.
    Играйте в Aviator и наслаждайтесь разнообразием врагов и уровней, которые позволят вам почувствовать себя настоящим авиатором.

LEAVE A REPLY

Please enter your comment!
Please enter your name here