How a program works in C++
Let's briefly go over the terms and syntax you used in the Hello World program. Breaking down the syntax can give you insight into the concepts behind the language and its structure.
Syntax breakdown
To better understand what's going on, it's helpful to go through the syntax of the program line by line, starting at the top row:
#include <iostream>
:iostream
is part of a standard library. Many components in a program are defined either by standard libraries or by libraries that you or a third party writes. The code usesiostream
, which is part of a standard library, to use the objectcout
to print something as output.#include <iostream>
using namespace std;
: A namespace helps prevent name conflicts in large projects. You want to use the functionalities of a namespace throughout the code without repeatedly calling the namespace when it's required. So, you declare the namespace at the beginning of the code. Also, the syntax that's required for usingcout
isstd::cout
. By adding the lineusing namespace std;
, you don't need to repetitively usestd
.#include <iostream> using namespace std;
int main()
: A function is a set of statements that perform a task together.main()
is a global function and the designated start of a program. Every C++ program has a mandatorymain()
function. Theint
used beforemain()
says that this function expects an integer to be returned.#include <iostream> using namespace std; int main() { cout << "Hello World\n"; return 0; }
cout
:cout
prints a specific string as output.std::cout
is part of a collection of data and operations of thestd::ostream
class.#include <iostream> using namespace std; int main() { cout << "Hello World\n"; return 0; }
"Hello World"
: The output Hello World is set in double quotes (""
). You can usestd::string
in many ways. The main two ways to usestd::string
are as a C-string (character array) or as astring
class.char
is a primitive data type.We use different data types, like integer, float, double, and char, to express and store values. For example, an integer might be
123
, a float might be9.02
, and a char might be'a'
.\n
: Use\n
to terminate the string and move to the next line.\n
is called an escape sequence.return 0
: When you declare theint main()
function, you specifyint
to declare the function, which returns an integer. If the function is preceded byint
, it expects an integer in the return. By usingreturn 0
, you make sure that an integer is returned to complete the function. Here,return
is the keyword and0
is the integer.#include <iostream> using namespace std; int main() { cout << "Hello World\n"; return 0; }