The program has been structured in different lines in order to be more readable, but in C++, we do not have strict rules on how to separate instructions in different lines. For example, instead of
int main ()
{
cout << " Hello World!";
return 0;
}
We could have written:
int main () { cout << "Hello World!"; return 0; }
Let us add an additional instruction to our first program:
// my second program in C++#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
Output:
Hello World! I'm a C++ program
int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; }
We were also free to divide the code into more lines if we considered it more convenient:
int main ()
{
cout <<
"Hello World!";
cout
<< "I'm a C++ program";
return 0;
}
And the result would again have been exactly the same as in the previous examples.
int main ()
{
cout << " Hello World!";
return 0;
}
We could have written:
int main () { cout << "Hello World!"; return 0; }
All in just one line and this would have had exactly the same meaning as the previous code. In C++, the separation between statements is specified with an ending semicolon (;) at the end of each one, so the separation in different code lines does not matter at all for this purpose. We can write many statements per line or write a single statement that takes many code lines. The division of code in different lines serves only to make it more legible and schematic for the humans that may read it.
// my second program in C++#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
Output:
Hello World! I'm a C++ program
In this case, we performed two insertions into cout in two different statements. Once again, the separation in
different lines of code has been done just to give greater readability to the program, since main could have been perfectly valid defined this way:
int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; }
We were also free to divide the code into more lines if we considered it more convenient:
int main ()
{
cout <<
"Hello World!";
cout
<< "I'm a C++ program";
return 0;
}
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 and do not produce any code by themselves. Preprocessor directives must be specified in their own line and do not have to end with a semicolon (;).