Docs

README

C++ Syntax and Program Structure

Table of Contents

  1. Program Structure Overview
  2. Tokens and Lexical Elements
  3. Identifiers and Naming
  4. Keywords
  5. Statements and Expressions
  6. Blocks and Scope
  7. Code Formatting and Style
  8. Header Files
  9. The Main Function
  10. Common Syntax Errors

Program Structure Overview

Every C++ program follows a specific structure. Understanding this structure is fundamental to writing correct programs.

Basic Program Template

┌────────────────────────────────────────────┐
│  PREPROCESSOR DIRECTIVES                   │
│  #include <iostream>                       │
│  #define CONSTANT 100                      │
├────────────────────────────────────────────┤
│  GLOBAL DECLARATIONS                       │
│  const int MAX_SIZE = 1000;                │
│  void helperFunction();                    │
├────────────────────────────────────────────┤
│  MAIN FUNCTION                             │
│  int main() {                              │
│      // Program execution starts here      │
│      return 0;                             │
│  }                                         │
├────────────────────────────────────────────┤
│  FUNCTION DEFINITIONS                      │
│  void helperFunction() {                   │
│      // Implementation                     │
│  }                                         │
└────────────────────────────────────────────┘

Execution Flow

Program Start
     │
     ▼
┌─────────────────┐
│ Global init     │ ← Static/global variables initialized
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ main() called   │ ← Execution begins here
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Statements      │ ← Execute top to bottom
│ execute         │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ return value    │ ← Return to OS
└─────────────────┘

Tokens and Lexical Elements

Tokens are the smallest individual units in a C++ program. The compiler breaks your code into tokens during lexical analysis.

Types of Tokens

Token TypeExamplesDescription
Keywordsint, return, if, classReserved words with special meaning
IdentifiersmyVariable, calculateSumNames for variables, functions, etc.
Literals42, 3.14, "hello", 'A'Fixed values in code
Operators+, -, *, ==, &&Symbols for operations
Separators;, ,, {}, (), []Punctuation for structure
Comments// text, /* text */Ignored by compiler

Literal Types

// Integer literals
int decimal = 42;           // Decimal (base 10)
int octal = 052;            // Octal (base 8) - starts with 0
int hex = 0x2A;             // Hexadecimal (base 16) - starts with 0x
int binary = 0b101010;      // Binary (C++14) - starts with 0b

// Floating-point literals
double d1 = 3.14;           // Standard notation
double d2 = 3.14e10;        // Scientific notation
double d3 = 314e-2;         // 3.14

// Character literals
char c1 = 'A';              // Single character
char c2 = '\n';             // Escape sequence (newline)
char c3 = '\x41';           // Hex value (65 = 'A')

// String literals
const char* s1 = "Hello";           // C-style string
std::string s2 = "World";           // C++ string
const char* s3 = R"(raw "string")"; // Raw string (C++11)

// Boolean literals
bool b1 = true;
bool b2 = false;

// Pointer literal
int* ptr = nullptr;         // Null pointer (C++11)

Digit Separators (C++14)

// Use single quotes to separate digits for readability
long population = 7'900'000'000;
double avogadro = 6.022'140'76e23;
int binary = 0b1111'0000'1111'0000;

Identifiers and Naming

Identifiers are names you give to variables, functions, classes, and other entities.

Rules for Valid Identifiers

RuleValidInvalid
Start with letter or underscorename, _count2name, @var
Contain letters, digits, underscoresvar1, my_varmy-var, my.var
Case-sensitiveNamename-
Not a keywordmyClassclass
No spacesmyVariablemy variable

Naming Conventions

Variables and Functions

// camelCase (most common for variables/functions)
int studentCount;
void calculateTotal();
bool isValid;

// snake_case (also common)
int student_count;
void calculate_total();
bool is_valid;

Classes and Types

// PascalCase (standard for classes)
class StudentRecord {};
struct Point2D {};
enum class Color {};

Constants

// SCREAMING_SNAKE_CASE (traditional)
const int MAX_BUFFER_SIZE = 1024;
#define PI 3.14159

// Or with 'k' prefix (Google style)
const int kMaxBufferSize = 1024;

Private Members

class Example {
private:
    int m_value;      // m_ prefix
    int value_;       // Trailing underscore
    int _value;       // Leading underscore (avoid - reserved)
};

Best Practices

DO:

int userAge;                    // Descriptive
bool hasPermission;             // Boolean as question
void calculateMonthlyPayment(); // Verb for functions
const int MAX_RETRIES = 3;      // Caps for constants

DON'T:

int x;                          // Too short
int userAgeInYearsInteger;      // Too verbose
int _reserved;                  // Reserved prefix
int __dunderVar;                // Double underscore reserved

Keywords

Keywords are reserved words with special meanings. You cannot use them as identifiers.

C++ Keywords (Complete List)

Fundamental Types:
bool, char, char8_t, char16_t, char32_t, wchar_t,
short, int, long, signed, unsigned, float, double, void

Type Modifiers:
const, volatile, mutable, constexpr, consteval, constinit

Storage Classes:
auto, register, static, extern, thread_local

Control Flow:
if, else, switch, case, default,
for, while, do, break, continue, goto, return

Object-Oriented:
class, struct, union, enum, public, private, protected,
virtual, override, final, friend, this

Templates & Generics:
template, typename, concept, requires

Exceptions:
try, catch, throw, noexcept

Memory:
new, delete, sizeof, alignof, alignas

Operators:
and, and_eq, bitand, bitor, compl, not, not_eq,
or, or_eq, xor, xor_eq, operator

Type Casting:
const_cast, dynamic_cast, reinterpret_cast, static_cast

Other:
namespace, using, typedef, decltype, typeid,
inline, explicit, export, extern, asm
nullptr, true, false, static_assert, co_await, co_return, co_yield

Context-Sensitive Keywords

Some words have special meaning only in certain contexts:

// 'override' - only meaningful after virtual function
class Derived : public Base {
    void method() override;  // Keyword here
};
int override = 5;  // Valid variable name

// 'final' - only meaningful for classes/virtual functions
class Final final {};  // Keyword
int final = 10;        // Valid variable name

Statements and Expressions

Expressions

An expression is any code that produces a value:

// Simple expressions
42                      // Literal expression
x                       // Variable expression
x + y                   // Arithmetic expression
x > 0                   // Comparison expression
x = 5                   // Assignment expression (value is 5)
func()                  // Function call expression

// Compound expressions
(a + b) * c
x > 0 ? 1 : -1          // Ternary expression
a = b = c = 0           // Chained assignment

Statements

A statement is a complete instruction that performs an action:

// Expression statement (expression + semicolon)
x = 5;
cout << "Hello";
doSomething();

// Declaration statement
int count = 0;
string name = "Alice";

// Compound statement (block)
{
    int temp = a;
    a = b;
    b = temp;
}

// Control statements
if (x > 0) { ... }
for (int i = 0; i < 10; i++) { ... }
while (running) { ... }

// Jump statements
return value;
break;
continue;
goto label;  // Avoid using goto

// Null statement (empty)
;  // Does nothing, but valid

Statement vs Expression

┌─────────────────────────────────────────────┐
│ Expression: Produces a value                │
│ Statement: Performs an action               │
├─────────────────────────────────────────────┤
│ x + y         ← Expression (value)          │
│ x + y;        ← Statement (action)          │
│                                             │
│ x = 5         ← Expression (value is 5)     │
│ x = 5;        ← Statement (assigns 5 to x)  │
└─────────────────────────────────────────────┘

Blocks and Scope

Code Blocks

A block is a group of statements enclosed in braces {}:

// Function block
void function() {
    // Block content
}

// Control structure block
if (condition) {
    // if-block
} else {
    // else-block
}

// Standalone block
{
    int temp = x;
    x = y;
    y = temp;
}  // temp is destroyed here

Scope Rules

Scope determines where a variable is accessible:

┌─────────────────────────────────────────────────┐
│ GLOBAL SCOPE                                    │
│ int globalVar = 10;                             │
│                                                 │
│ ┌─────────────────────────────────────────────┐ │
│ │ FUNCTION SCOPE (main)                       │ │
│ │ int localVar = 20;                          │ │
│ │                                             │ │
│ │ ┌─────────────────────────────────────────┐ │ │
│ │ │ BLOCK SCOPE (if)                        │ │ │
│ │ │ int blockVar = 30;                      │ │ │
│ │ │ // Can access: globalVar, localVar,     │ │ │
│ │ │ //             blockVar                 │ │ │
│ │ └─────────────────────────────────────────┘ │ │
│ │ // Cannot access blockVar here              │ │
│ └─────────────────────────────────────────────┘ │
│                                                 │
└─────────────────────────────────────────────────┘

Variable Shadowing

int value = 100;  // Global

void function() {
    int value = 50;  // Shadows global

    {
        int value = 25;  // Shadows function-local
        cout << value;   // Prints 25
    }

    cout << value;       // Prints 50
    cout << ::value;     // Prints 100 (global scope operator)
}

Lifetime vs Scope

AspectScopeLifetime
DefinitionWhere name is visibleWhen object exists in memory
Determined byBlock structureStorage class
ExampleLocal variablesStatic variables outlive scope
void function() {
    static int count = 0;  // Lifetime: entire program
                           // Scope: only this function
    count++;
}

Code Formatting and Style

Indentation

Use consistent indentation (typically 2 or 4 spaces):

// 4-space indentation
void process() {
    if (condition) {
        for (int i = 0; i < 10; i++) {
            doSomething(i);
        }
    }
}

Brace Styles

K&R / One True Brace Style (OTBS)

if (condition) {
    // code
} else {
    // code
}

Allman Style

if (condition)
{
    // code
}
else
{
    // code
}

Google Style (Modified K&R)

if (condition) {
    // code
} else {
    // code
}

// Functions use Allman for definition
void Function()
{
    // code
}

Line Length and Breaking

// Keep lines under 80-100 characters
// Break long lines sensibly

// Long function call
result = calculateSomethingComplex(
    firstArgument,
    secondArgument,
    thirdArgument
);

// Long condition
if (isValid &&
    hasPermission &&
    meetsRequirements) {
    // code
}

// Long string
string message = "This is a very long message "
                 "that spans multiple lines "
                 "using automatic concatenation.";

Whitespace

// Spaces around operators
int sum = a + b;
bool valid = x > 0 && y < 100;

// No space before semicolon
doSomething();

// Space after keywords
if (condition)
for (int i = 0; i < n; i++)
while (running)

// Consistent function style
void function(int param)   // Space before paren or not - be consistent
void function (int param)  // Both are valid

Header Files

Purpose of Headers

Headers declare interfaces that can be shared across multiple source files:

┌─────────────────┐     ┌─────────────────┐
│   math.h        │     │   main.cpp      │
├─────────────────┤     ├─────────────────┤
│ // Declarations │     │ #include "math.h"│
│ int add(int,int)│────▶│                 │
│ int sub(int,int)│     │ int main() {    │
└─────────────────┘     │   add(2, 3);    │
                        │ }               │
┌─────────────────┐     └─────────────────┘
│   math.cpp      │
├─────────────────┤
│ #include "math.h"
│ int add(int a,  │
│         int b) {│
│   return a + b; │
│ }               │
└─────────────────┘

Header Guards

Prevent multiple inclusion:

// Method 1: Traditional include guards
#ifndef MYHEADER_H
#define MYHEADER_H

// Header content here

#endif // MYHEADER_H

// Method 2: Pragma once (widely supported, non-standard)
#pragma once

// Header content here

What Goes in Headers

In Header (.h/.hpp)In Source (.cpp)
Function declarationsFunction definitions
Class declarationsMethod implementations
Inline functionsLarge function bodies
Templates (usually)Static variable definitions
ConstantsMain function
Type definitions

Include Order

// Recommended order (Google style):
#include "my_project_header.h"  // Related header first

#include <iostream>              // C++ standard library
#include <vector>
#include <string>

#include <cstdlib>              // C library headers
#include <cmath>

#include "other_project_headers.h"  // Other project headers
#include "utility/helpers.h"

// Within each group, sort alphabetically

The Main Function

Valid Main Signatures

// Standard forms
int main() { return 0; }
int main(int argc, char* argv[]) { return 0; }
int main(int argc, char** argv) { return 0; }

// With environment (implementation-defined)
int main(int argc, char* argv[], char* envp[]) { return 0; }

Command-Line Arguments

// argc = argument count
// argv = argument vector (array of C-strings)

int main(int argc, char* argv[]) {
    // argv[0] is always the program name
    cout << "Program: " << argv[0] << endl;

    // argv[1] through argv[argc-1] are arguments
    for (int i = 1; i < argc; i++) {
        cout << "Arg " << i << ": " << argv[i] << endl;
    }

    return 0;
}
# Running with arguments:
./program hello world 123

# Output:
# Program: ./program
# Arg 1: hello
# Arg 2: world
# Arg 3: 123

Return Values

int main() {
    // Success
    return 0;
    return EXIT_SUCCESS;  // From <cstdlib>

    // Failure
    return 1;
    return EXIT_FAILURE;  // From <cstdlib>

    // If no return, 0 is implied (only for main)
}
# Check return value in shell:
./program
echo $?  # Prints 0 for success

Common Syntax Errors

Missing Semicolons

// Error: missing semicolon
int x = 5
int y = 10;

// Fixed:
int x = 5;
int y = 10;

Mismatched Braces

// Error: missing closing brace
if (x > 0) {
    doSomething();

// Fixed:
if (x > 0) {
    doSomething();
}

Wrong Operator

// Error: assignment instead of comparison
if (x = 5) {  // Always true, assigns 5 to x

// Fixed:
if (x == 5) {  // Comparison

Case Sensitivity

// Error: wrong case
Int x = 5;    // 'Int' is not 'int'
COUT << x;    // 'COUT' is not 'cout'

// Fixed:
int x = 5;
cout << x;

Undefined Variables

// Error: using undeclared variable
cout << value;  // 'value' not declared

// Fixed:
int value = 42;
cout << value;

Type Mismatches

// Error: incompatible types
int x = "hello";  // Can't assign string to int

// Fixed:
string x = "hello";
// or
int x = 42;

Header Issues

// Error: using cout without include
int main() {
    cout << "Hello";  // Error: cout not declared
}

// Fixed:
#include <iostream>
using namespace std;

int main() {
    cout << "Hello";
}

Summary

Understanding C++ syntax and structure is foundational:

  1. Tokens: Code is made of keywords, identifiers, literals, operators, separators
  2. Naming: Follow conventions for readability and consistency
  3. Statements: Complete instructions ending in semicolons
  4. Blocks: Code grouped in braces with defined scope
  5. Headers: Share declarations across files
  6. Main: Entry point with standard signatures

Quick Reference

// Complete minimal program structure
#include <iostream>        // Preprocessor directive
using namespace std;       // Namespace declaration

const int MAX = 100;       // Global constant

void helper();             // Function declaration

int main() {               // Entry point
    int x = 10;            // Local variable
    helper();              // Function call
    return 0;              // Exit status
}

void helper() {            // Function definition
    cout << "Helper" << endl;
}

Previous: Introduction | Next: Input/Output

README - C++ Tutorial | DeepML