Docs

program structure

📐 C++ Program Structure

The Anatomy of a C++ Program

Every C++ program follows a specific structure. Understanding this structure is crucial for writing correct code.

// 1. PREPROCESSOR DIRECTIVES
#include <iostream>
#include <string>
#define MAX_SIZE 100

// 2. USING DECLARATIONS (optional)
using namespace std;
// or selectively:
// using std::cout;
// using std::endl;

// 3. GLOBAL DECLARATIONS (use sparingly)
const double PI = 3.14159;

// 4. FUNCTION PROTOTYPES (declarations)
void greet(string name);
int add(int a, int b);

// 5. THE MAIN FUNCTION
int main() {
    // Program execution starts here
    greet("World");
    cout << "Sum: " << add(5, 3) << endl;
    return 0;
}

// 6. FUNCTION DEFINITIONS
void greet(string name) {
    cout << "Hello, " << name << "!" << endl;
}

int add(int a, int b) {
    return a + b;
}

1. Preprocessor Directives

// Include standard libraries
#include <iostream>      // For cout, cin
#include <string>        // For string class
#include <vector>        // For vector container
#include <cmath>         // For math functions

// Include your own headers
#include "myheader.h"    // Searches current directory first
#include <myheader.h>    // Searches system directories

// Define constants
#define PI 3.14159
#define MAX(a,b) ((a) > (b) ? (a) : (b))

// Conditional compilation
#ifdef DEBUG
    #define LOG(x) cout << x << endl
#else
    #define LOG(x)
#endif

Header Guards

// myheader.h
#ifndef MYHEADER_H      // If not defined
#define MYHEADER_H      // Define it

// Your declarations here
void myFunction();

#endif                  // End the guard

// Modern alternative (most compilers)
#pragma once

2. Namespaces

Namespaces prevent naming conflicts:

#include <iostream>

// WITHOUT using namespace
int main() {
    std::cout << "Hello" << std::endl;
    std::string name = "World";
    return 0;
}

// WITH using namespace (not recommended for large projects)
using namespace std;

int main() {
    cout << "Hello" << endl;
    string name = "World";
    return 0;
}

// SELECTIVE using (recommended)
using std::cout;
using std::endl;

int main() {
    cout << "Hello" << endl;
    std::string name = "World";  // Still need std:: for string
    return 0;
}

Creating Your Own Namespace

namespace MyMath {
    const double PI = 3.14159;

    double square(double x) {
        return x * x;
    }

    double cube(double x) {
        return x * x * x;
    }
}

int main() {
    cout << MyMath::PI << endl;
    cout << MyMath::square(5) << endl;
    return 0;
}

3. The main() Function

Standard Forms

// Form 1: No arguments
int main() {
    return 0;
}

// Form 2: With command-line arguments
int main(int argc, char* argv[]) {
    // argc = argument count
    // argv = argument values

    cout << "Program name: " << argv[0] << endl;
    cout << "Arguments: " << argc - 1 << endl;

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

    return 0;
}

// Alternative form
int main(int argc, char** argv) {
    // Same as above
    return 0;
}

Return Values

int main() {
    // return 0;         // Success
    // return 1;         // General error
    // return EXIT_SUCCESS;  // Same as 0 (from <cstdlib>)
    // return EXIT_FAILURE;  // Same as 1

    return 0;
}

4. Statements and Blocks

Statement Types

int main() {
    // 1. Declaration statement
    int x;

    // 2. Assignment statement
    x = 10;

    // 3. Declaration + initialization
    int y = 20;

    // 4. Expression statement
    x + y;  // Valid but useless

    // 5. Function call statement
    cout << x << endl;

    // 6. Return statement
    return 0;
}

Code Blocks

int main() {
    int x = 10;  // Scope: entire main()

    {   // New block - creates new scope
        int y = 20;  // Scope: only this block
        cout << x << endl;  // Can access x
        cout << y << endl;  // Can access y
    }

    cout << x << endl;  // Can access x
    // cout << y << endl;  // ERROR! y is out of scope

    return 0;
}

5. Semicolons and Whitespace

Semicolons

int main() {
    int x = 10;    // Semicolon ends statements
    int y = 20;

    // Multiple statements on one line (not recommended)
    int a = 1; int b = 2; int c = 3;

    // One statement across multiple lines (fine)
    int sum = 1 + 2 + 3 + 4 + 5
            + 6 + 7 + 8 + 9 + 10;

    // These DON'T need semicolons:
    // - Function definitions after }
    // - if/else/for/while after }
    // - Class definitions DO need ; after }

    return 0;
}

class MyClass {
    // ...
};  // <-- Semicolon required after class!

Whitespace

// Whitespace is generally ignored
int main(){int x=10;int y=20;return 0;}  // Valid but terrible

// Good formatting
int main() {
    int x = 10;
    int y = 20;
    return 0;
}

// Consistency is key - pick a style and stick to it

Complete Program Template

/**
 * @file program.cpp
 * @brief Description of what this program does
 * @author Your Name
 * @date 2024
 */

// Standard library includes
#include <iostream>
#include <string>
#include <vector>

// Project includes
// #include "myheader.h"

// Using declarations
using std::cout;
using std::cin;
using std::endl;
using std::string;

// Constants
const int MAX_SIZE = 100;

// Function prototypes
void initialize();
void processData();
void cleanup();

/**
 * @brief Main entry point
 * @return 0 on success, non-zero on failure
 */
int main() {
    initialize();
    processData();
    cleanup();
    return 0;
}

// Function definitions
void initialize() {
    cout << "Initializing..." << endl;
}

void processData() {
    cout << "Processing..." << endl;
}

void cleanup() {
    cout << "Cleaning up..." << endl;
}

Exercises

  1. Create a program with multiple functions
  2. Create your own namespace with some functions
  3. Write a program that uses command-line arguments
  4. Practice with different code block scopes

Next: Input and Output

Program Structure - C++ Tutorial | DeepML