C++ Syntax and Namespaces
Syntax is the set of rules for writing C++ code. The compiler is strict about them, but there are not many to learn.
Statements, semicolons and blocks
A statement is one instruction, ending with a semicolon. Statements run from top to bottom. Curly braces { } group statements into a block, such as the body of main. Every { needs a matching }, and the code inside is indented to show the structure.
#include <iostream>
int main() {
std::cout << "One\n";
std::cout << "Two\n";
{
std::cout << "Inside a block\n";
}
return 0;
}One Two Inside a block
Case and whitespace
C++ is case sensitive: cout, Cout and COUT are different names. Keywords such as int, if and return are lower case. Spaces and line breaks between the parts of a statement do not matter to the compiler; use them to make the code readable.
Namespaces
Large programs and libraries use many names. A namespace groups names so that two libraries can both have a function called print without a clash. The standard library is in std, and :: reaches a name inside a namespace: std::cout. You can make your own:
#include <iostream>
namespace geometry {
double square(double x) { return x * x; }
}
namespace finance {
double square(double x) { return x * x * 100; } // a different square
}
int main() {
std::cout << geometry::square(3) << "\n";
std::cout << finance::square(3) << "\n";
return 0;
}9 900
using
using std::cout; makes one name usable without std::; using namespace std; does it for every name in std. They save typing in small programs. Never put using namespace std; in a header file, because every file that includes it would get all of std's names.
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string language = "C++";
cout << "Learning " << language << "\n";
return 0;
}Learning C++
Practice exercises
- Write a namespace
schoolwith a function that prints the school's name, and call it frommain. - Change
couttoCoutand read the error. - Remove the closing
}ofmainand see where the compiler reports the problem.