1.1 Hello world
This is a hello world program in C++:
#include <iostream>
int main()
{
std::cout << "Hello C++!" << std::endl;
return 0;
}Write the above code in hello.cpp, then you can compile it with
g++ hello.cpp -o hello and run ./hello (you can replace g++ with clang++
or any other compiler).
A couple of things to note here:
Every C++ executable (as opposed to library) must have a main() function that
returns int. Returning 0 signifies that the program terminates without errors.
The final return 0; statement can be omitted in the main() function.
#include is a preprocessor. We’ll meet more preprocessors in the future, for now
just accept that they are “naive macros” that are “expanded” before the actual
compilation.
Here #include copies the content of file called iostream, which has tens of
thousands lines, and pastes it here. Yes, it literally does so, and you can check
this by running g++ -E main.c, which “expands” all preprocessor statements.
iostream contains definitions of functions and objects such as std::cout and
std::endl, which are used for IO manipulations. cout stands for “character
output,” and endl stands for “endline” (it appends \n and flushes the buffer).
<< is the bitwise left shift operator, and the designers of C++ decided that
overloading bitwise shift operators for cout and cin can make C++ look fancy
from the beginning. That’s why we need to learn yet another special syntax.
iostream also introduces another function into scope, the C-compatible printf into scope,
which can also be used to print “Hello world.”
printf("Hello from printf\n");Since we do not have string interpolation of variable in this case, we can also use puts:
puts("Hello from printf"); // newline automatically appendedNow you might begin to wonder, why isn’t std::cout called std::iostream::cout,
and why printf can be called without any prefix. This is because in C++ filenames
have no relationships to namespaces by default. namespace is similar to Rust’s mod,
but more flexible. In this case, the iostream file contains something conceptually like this:
void printf(...);
namespace std {
class cout {}
class endl {}
}printf isn’t placed inside std because it is a heritage from C. Many other C functions
are also available in C++, and they can be distinguished by the absence of the std:: prefix.