Skip to content

C++ Basic Syntax

A C++ program is fundamentally a collection of functions and types (like classes and structures). Object-Oriented Programming (OOP) views a program as a collection of interacting objects.

  • Object: An instance of a class. It has state (data members/variables) and behavior (member functions/methods). Example: A specific Car object might have states like color = "red", currentSpeed = 50, and behaviors like accelerate(), brake().
  • Class: A blueprint or template for creating objects. It defines the properties (data members) and actions (member functions) that all objects of that class will have.
  • Method (Member Function): A function associated with a class. Methods define the behavior of objects and operate on their data.
  • Data Member (Instance Variable): Variables defined within a class that hold the state of an object. Each object (instance) of the class has its own copy of these variables.

Let’s examine a simple “Hello, World!” program:

// Include the Input/Output Stream library header
#include <iostream>
// main() is where program execution begins.
int main() {
// Use std::cout to print to the console
// std::endl inserts a newline and flushes the stream
std::cout << "Hello, World!" << std::endl;
// Return 0 to indicate successful execution
return 0;
}

Let’s break down the parts:

  • #include <iostream>: This is a preprocessor directive. It tells the compiler to include the contents of the <iostream> header file, which contains declarations for standard input/output operations like std::cout.
  • int main(): This is the main function. Execution of every C++ program begins here. The int indicates that main returns an integer value to the operating system (conventionally, 0 means success).
  • { ... }: Braces define a block of code, also known as a compound statement. The body of the main function is enclosed in braces.
  • std::cout << "Hello, World!" << std::endl;: This is a statement. std::cout is the standard output stream object (usually the console). The << operator is the stream insertion operator, used here to send the string literal "Hello, World!" and the manipulator std::endl (end line) to std::cout.
  • std:: Namespace Prefix: cout and endl are part of the standard namespace (std). Using std:: qualifies their names. It’s generally good practice to use the std:: prefix rather than using namespace std; at the global scope to avoid potential name collisions.
  • return 0;: This statement terminates the main function and returns the value 0 to the calling process (usually the operating system), indicating successful completion.
  • //: Single-line comments start with // and continue to the end of the line.
  • /* ... */: Multi-line comments start with /* and end with */.

To compile and run your C++ code, you typically need a C++ compiler (like g++, Clang, or MSVC) installed.

  • Save the code above in a file named hello.cpp.
  • Open a terminal or command prompt.
  • Navigate to the directory where you saved the file.
  • Compile the code using your compiler. It’s good practice to specify the C++ standard version (e.g., C++17 or C++20) and an output filename:
  • g++ hello.cpp -o hello -std=c++17 (for g++ or Clang)
  • cl hello.cpp /std:c++17 /EHsc /Fe:hello.exe (for MSVC)
  • If compilation is successful (no errors), an executable file (hello or hello.exe) will be created.
  • Run the executable:
  • ./hello (on Linux/macOS)
  • hello.exe or .\hello.exe (on Windows)
  • You should see Hello, World! printed on your console.

For larger projects, managing compilation manually becomes tedious. Build systems like CMake or Meson, along with build tools like Make or Ninja, are commonly used to automate the build process.

In C++, the semicolon (;) acts as a statement terminator. Each individual instruction or declaration usually ends with a semicolon.

// Three distinct statements:
int x = 10;
x = x + 5;
std::cout << x << std::endl;

A block (or compound statement) is a sequence of zero or more statements enclosed in curly braces {}. Blocks group statements logically, often used as the body of functions, loops, or conditional statements. Blocks also define scope.

{
int y = 20; // y is local to this block
std::cout << "Inside block." << std::endl;
} // y goes out of scope here

Whitespace (spaces, tabs, newlines) is generally ignored by the compiler, except when it’s needed to separate tokens (like int and main). You can format your code with indentation and spacing to improve readability.

An identifier is a name used to identify entities like variables, functions, classes, types, namespaces, etc. Rules for identifiers:

  • Must begin with a letter (a-z, A-Z) or an underscore (_).
  • Can be followed by letters, underscores, or digits (0-9).
  • Cannot contain punctuation characters like @, $, %, or spaces.
  • Are case-sensitive: myVariable and myvariable are different identifiers.
  • Cannot be the same as a C++ keyword.
  • Identifiers containing a double underscore (__) or starting with an underscore followed by an uppercase letter are reserved for the implementation and should be avoided.

Examples of valid identifiers:

value count temp_sensor _internalData MAX_SIZE MyClass processInput

Keywords are reserved words with special meaning in the C++ language. You cannot use them as identifiers. Here is a non-exhaustive list of common C++ keywords (including some from modern C++ standards):

Core TypesControl FlowLoopsUser TypesOOP/AccessMemory/PointersModifiersModern C++Exceptions/Misc
intdoublecharboolvoid
ifelseswitchcasedefault
forwhiledobreakcontinue
classstructenumunionnamespace
publicprivateprotectedvirtualoverride (C++11)
newdeletethisnullptr (C++11)using
conststaticexterninlinevolatile
auto (C++11)decltype (C++11)constexpr (C++11)noexcept (C++11)template
trycatchthrowreturnsizeof

Note: This list is illustrative. Consult C++ documentation for the complete set of keywords for a specific standard version.

Historically, C++ supported trigraph sequences (three-character sequences starting with ?? representing single characters like #, [, ], etc.) for environments lacking certain characters. Trigraphs were confusing and rarely used; they were removed from the C++ standard in C++17. You should not use them in modern C++ code.