Explain the basic structure of c++ program with an example
Answers
Answer:
(PLZ BRAINIEST )
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 the main 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!";
}
Edit & Run
We could have written:
int main () { std::cout << "Hello World!"; }
Edit & Run
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
Edit & Run
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 "; }
Edit & Run
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";
}
Edit & Run
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 (;)