C++ Syntax
Let's take a careful look at the building blocks of a C++ program. Here is a small program we will dissect:
#include <iostream>
using namespace std;
int main() {
cout << "Learning the syntax\n";
return 0;
}Learning the syntax
Line by line
| Line | Meaning |
|---|---|
#include <iostream> |
A preprocessor directive that makes the input/output library available. |
using namespace std; |
Lets you write cout instead of std::cout. |
int main() |
Declares the main function, where execution begins. int is its return type. |
{ ... } |
Curly braces mark the start and end of a block of code (here, the function body). |
cout << "..."; |
A statement that prints text. Every statement ends with ;. |
return 0; |
Ends main and reports success. |
Namespaces and std::
Everything in the C++ standard library lives in a namespace called std. A namespace is like a surname: it prevents name clashes between libraries. You can refer to library names in two ways:
#include <iostream>
int main() {
std::cout << "Fully qualified name\n";
using std::cout; // import just this one name
cout << "Short name after a using-declaration\n";
}Fully qualified name
Short name after a using-declaration
Note:
using namespace std;is fine for small examples and exercises, and you will see it in many lessons here. In large projects and especially in header files, preferstd::or targetedusing std::cout;declarations so that names do not collide.
Statements and semicolons
A statement is one instruction. C++ does not care about line breaks — it uses the semicolon to tell where a statement ends. That means these two lines are equivalent, although the first is much easier to read:
std::cout << "Hi";
std::cout
<<
"Hi"
;Forgetting a semicolon is the most common beginner error. The compiler usually reports it on the next line, because that is where it realises something is missing.
Whitespace and case sensitivity
- Spaces, tabs and blank lines are ignored (except inside strings). Use them to make code readable.
- C++ is case-sensitive:
main,MainandMAINare three different names.Coutwill not compile.
Blocks
Curly braces group statements. Functions, if statements and loops all use blocks. By convention, code inside a block is indented by 4 spaces:
#include <iostream>
using namespace std;
int main() {
cout << "Outer block\n";
{
cout << " Inner block\n";
}
cout << "Back outside\n";
}Outer block
Inner block
Back outside
Test yourself
What character ends most C++ statements?
- .
- :
- ;
- Newline
Which namespace contains the standard library?
- stl
- std
- cpp
- lib
Is Cout the same as cout in C++?
- Yes, C++ ignores case
- No, C++ is case-sensitive
- Only on Windows
- Only inside main