Introduction

C++ is a high-level, general-purpose programming language created as an extension of the C programming language. It combines both high-level and low-level language features, making it suitable for various applications, including systems/software development and game development.

  • Supports object-oriented programming paradigms with classes, inheritance, polymorphism, and encapsulation.
  • Offers low-level memory manipulation and high-level abstractions, allowing for efficient resource management.
  • Provides a comprehensive set of libraries for various functionalities like input/output operations, containers, algorithms, etc.
  • C++ is backward-compatible with C and supports procedural and object-oriented programming styles.
  • Offers control over hardware, making it suitable for systems programming.
What you should already know

This guide assumes you have a basic understanding of programming concepts and computer science fundamentals, including:

  • Knowledge of basic programming constructs like variables, control structures, and functions.
  • Familiarity with the command-line interface and working in a terminal or console environment.
C++ and C

C++ and C share fundamental similarities but also have crucial differences. While C++ extends C and inherits many of its features, it introduces object-oriented programming concepts and supports both procedural and object-oriented programming styles.

C++ enriches the C language by providing stronger type checking, a richer standard library, exception handling, namespaces, and templates. It maintains compatibility with C, allowing C code to run within a C++ environment. However, it extends C significantly, making it more suitable for modern software development needs with its support for high-level abstraction and efficient resource management.

Hello world

To get started with writing C++, open your preferred editor and write your first "Hello world" C++ code:

      
    #include <iostream>

    int main() {
        std::cout << "Hello, World!" << std::endl;
        return 0;
    }
            
Variables

You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.

A C++ identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because C++ is case sensitive, letters include the characters "A" through "Z" (uppercase) and "a" through "z" (lowercase).

You can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. Unicode escape sequences can also be used as characters in identifiers. Some examples of legal names are Number_hits, temp99, and _name.

Declaring variables

In C++, variables can be declared in various ways:

C++11 introduced the 'auto' keyword to declare variables with automatic type deduction. For example,

      
    auto x = 42;
            

This allows the compiler to automatically deduce the variable's type based on the assigned value.

Variables can be explicitly declared with a specified type. For instance,

      
    int x = 42;
            

This declares an integer variable 'x' and initializes it with the value 42.

Variables can also be declared without immediate initialization, like so:

      
    int y;
            

In this case, the variable 'y' is declared but not initialized. It may contain garbage or undefined values until explicitly assigned.

These methods enable the declaration of variables in C++, offering flexibility in specifying types and initializing values. The 'auto' keyword allows for automatic type inference, while explicit type declarations provide clarity in the variable's data type.

Variable scope

In C++, variables have different scopes depending on where they are declared:

Variables declared outside any function or block have global scope. They are accessible from any part of the program.

      
    int globalVariable = 10; // Global variable
            

Variables declared inside a function are local to that function and can only be accessed within it.

      
    void someFunction() {
        int localVariable = 20; // Local variable within someFunction()
    }
            

C++ supports block-level scoping where variables declared within a block (within curly braces) have scope limited to that block.

      
    if (true) {
        int blockVariable = 30; // Variable with block scope
    }
            

In C++, variables declared within a block are scoped to that block and its nested blocks. Once the block is exited, the variables cease to exist. This helps in managing variable lifetimes and prevents naming conflicts by limiting a variable's scope to a specific block of code.

Global variables

In C++, global variables are declared outside of any function and have a global scope, making them accessible from any part of the program.

      
    #include 
    using namespace std;

    int globalVariable = 10; // Global variable

    int main() {
        cout << "Global variable value: " << globalVariable << endl;
        return 0;
    }
            

Global variables in C++ persist throughout the program's execution, and their values can be accessed and modified from any function or block within the program. They are typically declared outside of any function and can be accessed using their name directly.

However, it's generally recommended to use global variables sparingly due to potential issues with program maintainability and unintended side effects caused by their unrestricted access across different parts of the program.

Constants

In C++, you can define constants using the const keyword. Constants are immutable values whose values cannot be changed once initialized.

      
    #include 
    using namespace std;

    const double PI = 3.14; // Constant declaration

    int main() {
        cout << "Value of PI: " << PI << endl;
        return 0;
    }
            

In C++, constants must be initialized upon declaration and cannot be reassigned a different value throughout the program's execution.

The scope of constants in C++ follows the same rules as other variables. They are accessible within the scope they are declared in and cannot have the same name as a variable or function within the same scope. Attempting to reassign a value to a constant will result in a compilation error.

Constants provide a way to define values that remain constant throughout the program, enhancing readability and ensuring that certain values do not change accidentally during program execution.

Data types

In C++, the data types are the building blocks used to define variables or functions. It includes fundamental data types, such as integral types, floating-point types, and compound types. Here's a brief overview:

  • Fundamental Types:
    • Integer types: Represent whole numbers. (e.g., int, short, long)
    • Floating-point types: Represent real numbers. (e.g., float, double)
    • Character types: Represent individual characters. (e.g., char)
    • Boolean type: Represents true or false values. (bool)
  • Derived Types:
    • Pointers: Hold memory addresses. (e.g., int*, char*)
    • References: Provide aliases to existing variables. (e.g., int&, char&)
  • Compound Types:
    • Arrays: Contain elements of the same type in a contiguous block of memory.
    • Structures: Group different data types under one name.
    • Classes: Similar to structures but also encapsulate methods and access specifiers.
    • Unions: Hold different data types in the same memory location.

C++ also supports modifiers, such as signed, unsigned, and const, to further refine the fundamental types. These data types allow you to define variables, functions, and classes, providing the foundation for creating robust applications.

if...else statement

In C++, the if statement is used to execute a block of code if a specified condition is true. It can be followed by an optional else statement to execute a block of code if the condition is false. Here is an explanation of the if...else statement in C++:

      
    if (condition) {
        // statement_1 runs if condition is true
    } else {
        // statement_2 runs if condition is false
    }
            

condition can be any expression that results in a Boolean value (true or false).

The if statement checks the given condition. If the condition evaluates to true, statement_1 inside the block will be executed; otherwise, statement_2 will be executed.

You can use multiple else if statements to check for multiple conditions in sequence:

      
    if (condition_1) {
        // statement_1
    } else if (condition_2) {
        // statement_2
    } else if (condition_n) {
        // statement_n
    } else {
        // statement_last
    }
            

If multiple conditions are present, only the block associated with the first condition that is true will be executed.

It's recommended to use curly braces {} even for single statements to avoid confusion and maintain code clarity.

Avoid using simple assignments within conditional expressions, as it can be mistaken for equality checking. For instance, use == for comparison instead of = inside the if condition.

If an assignment needs to be used within a conditional expression, enclose it in additional parentheses for clarity.

The if...else statement in C++ helps control program flow based on specified conditions and is a fundamental part of decision-making in programming logic.

while statement

In C++, the while loop executes a block of code repeatedly as long as a specified condition is true. Here's an explanation of the while statement in C++:

      
    while (condition) {
        // statements
    }
            

condition is a Boolean expression that is evaluated before each iteration of the loop.

The loop continues executing as long as the condition evaluates to true.

If the condition becomes false, the loop terminates, and control passes to the next statement following the while loop.

The block of code within the while loop (the statements) is executed repeatedly while the condition remains true.

The condition is checked before the execution of the statements inside the loop. If the condition initially evaluates to false, the loop body will not execute.

To avoid an infinite loop, ensure that the condition eventually becomes false during the loop execution.

      
    int n = 0;
    int x = 0;

    while (n < 3) {
        n++;
        x += n;
    }
            

With each iteration, n is incremented by 1 and added to x. Therefore, x and n take on the following values:

  • After the first iteration: n = 1 and x = 1
  • After the second iteration: n = 2 and x = 3
  • After the third iteration: n = 3 and x = 6

After the third iteration, the condition n < 3 becomes false, and the loop terminates.

Function declarations

In C++, function declarations or function definitions consist of:

      
    return_type function_name(parameter_list) {
        // Function body/statements
    }
            

return_type specifies the data type of the value returned by the function.

function_name is the identifier or name of the function.

parameter_list is a list of parameters (arguments) the function expects, enclosed in parentheses and separated by commas.

The function body consists of the statements enclosed in curly braces { }.

For example, the following code defines a simple function named square in C++:

      
    int square(int number) {
        return number * number;
    }
            

The function square takes an integer argument number.

The function body contains a single statement that multiplies the number argument by itself using the * operator and returns the result using the return statement.

In C++, parameters are passed by value by default. This means that changes made to the parameter within the function are limited to the function's scope and do not affect the original value passed to the function from outside.

Reference

The information provided here is based on various C++ programming resources including the C++ standard documents, official documentation, textbooks, and online tutorials.