Docsity
Docsity

Prepara i tuoi esami
Prepara i tuoi esami

Studia grazie alle numerose risorse presenti su Docsity


Ottieni i punti per scaricare
Ottieni i punti per scaricare

Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium


Guide e consigli
Guide e consigli


C++ programming language, Dispense di Programmazione C

Documento scritto da me in inglese sul linguaggio C++. La dispensa spiega il linguaggio, la sua sintassi e la sua logica in maniera chiara e semplice con illustrazioni chiave per trasmettere i concetti che spesso non vengono compresi in modo comprensibile. Si parte dalle basi fino alle struct passando per programmazione dinamica, puntatori, variabili globali e tutorial tecnici. Ogni argomento è corredato di esercizi svolti per comprendere meglio gli argomenti. Questo documento è adatto per chiunque indipendentemente dall'università/corso voglia approfondire la programmazione C++ in maniera strutturata e completa.

Tipologia: Dispense

2024/2025

In vendita dal 13/12/2024

giulio_russo
giulio_russo 🇮🇹

4.8

(42)

111 documenti

1 / 128

Toggle sidebar

Questa pagina non è visibile nell’anteprima

Non perderti parti importanti!

bg1
C++
💻
programming
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Anteprima parziale del testo

Scarica C++ programming language e più Dispense in PDF di Programmazione C solo su Docsity!

C++

programming

Index

  • What is Programming?
  • History, Purpose and Use Cases
  • Installing C++ and Setting Up IDE
  • Compiling and Running a C++ Program
  • Starting C++ program
  • Variables
  • Data Types
  • Variable names
  • Comments
  • Modifiers
  • Memory
  • Pre-processor directives
  • Importing libraries
  • Input/Output
  • Stream Buffering
  • Namespaces
  • Standard namespace
  • Qualifiers
  • Const
  • Arighmetic Operators
  • Compound Assignment Operators
  • Increment and Decrement Operators
  • Comparison Operators
  • Logical Operators
  • Casting and Type conversion
  • Bohom-Jacopini theorem
  • Control flow
  • Loops
  • Manage flow
  • Exercise
  • Functions
  • Exercise
  • Recursion
  • Exercise
  • Global variables
  • Arrays
  • Exercise
  • Characters array
  • Exercise
  • Multidimensional arrays
  • Exercise
  • Pointers
  • Exercise
  • Passing parameters
  • Exercise
  • Pointers and Arrays
  • Exercise
  • Dynamic memory
  • Heap memory
  • Exercise
  • Struct
  • Exercise
  • Enumerate
  • Enumerate class
  • Exercise
  • Multiple files
  • How to compile multiple files
  • Exercise
  • C++ code translation
  • Debug suggestions
  • Thanks

History, Purpose and Use Cases

C++ is a powerful, general-purpose programming language that was developed by Bjarne Stroustrup in 1979 as an extension of the C programming language. Originally called "C with Classes," it was designed to bring the benefits of object-oriented programming (OOP) to C, a language widely known for its efficiency and close relationship with system hardware. The name was later changed to C++ in 1983, reflecting the language’s evolution, with "++" symbolizing the increment operator in C, hinting at its enhancement over the original language. C++ was built to offer both high-level abstractions for easier software design and low- level memory control, making it versatile and performance-oriented. C++ was created to solve some of the limitations of C, particularly the need for a language that could handle both complex software systems and hardware-level tasks. Its core purpose is to provide developers with the tools to write efficient, high- performance code while maintaining the flexibility to manage system resources directly, such as memory allocation and hardware interaction. This balance makes C++ well-suited for system programming, game development, and applications requiring real-time processing. Over the years, C++ has undergone several updates and revisions, with modern features being added through versions like C++11, C+ +14, C++17, and C++20. These updates introduced features like smart pointers, lambda expressions, and concurrency support, ensuring that the language remains relevant for modern development needs. C++ is widely used in a variety of industries and applications. In systems programming, it is often the go-to choice for developing operating systems, device drivers, and embedded systems due to its fine-grained control over hardware and memory. In game development, C++ powers many game engines like Unreal Engine, where performance and real-time rendering are critical. Additionally, C++ is used in high-performance computing, financial applications (such as algorithmic trading systems), and even in the development of large-scale applications like web browsers, including Google Chrome and Firefox. Its flexibility, efficiency, and widespread adoption make C++ a crucial tool for any developer working on resource- intensive or performance-critical applications.

Installing C++ and Setting Up IDE

To start programming in C++, you need two main components: a C++ compiler and an Integrated Development Environment (IDE). The compiler is responsible for translating your C++ code into machine code that your computer can execute, while the IDE helps you write, debug, and manage your code more efficiently. Some popular IDEs for C++ include Visual Studio Code (VSCode), CLion, and Visual Studio. Although the installation steps are similar across platforms, certain steps will differ depending on whether you are using Windows or macOS/Linux. Step 1: Install a C++ Compiler

  • Windows: The easiest way to install a C++ compiler on Windows is to use MinGW (Minimalist GNU for Windows). MinGW provides GCC, which is one of the most widely used compilers.
    1. Download MinGW from the MinGW-w64 website.
    2. Run the installer and select the architecture (32-bit or 64-bit) based on your system.
    3. During installation, ensure that the "Basic Setup" includes the GCC compiler.
    4. Once installed, add the MinGW bin directory (e.g., C:\MinGW\bin) to your system’s Path environment variable. This step is necessary so that your system can recognize the g++ command from the terminal. Alternatively, you can install Visual Studio (a different IDE), which comes with Microsoft’s C++ compiler, MSVC.
  • macOS: On macOS, the easiest way to install the C++ compiler is by using Xcode Command Line Tools, which provides Clang, a highly efficient C++ compiler.
    1. Open a terminal and run the following command: xcode-select --install
    2. Follow the on-screen instructions to install Xcode’s command-line tools, which includes the Clang C++ compiler. Alternatively, if you want to use GCC, you can install it via Homebrew (a package manager for macOS):
    3. Install Homebrew if you don’t already have it by running: /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/ install/HEAD/install.sh)"
    4. Once Homebrew is installed, you can install GCC by running: brew install gcc
  • Linux: Most Linux distributions come with GCC pre-installed. You can check if GCC is already installed by opening a terminal and running: gcc --version

Compiling and Running a C++ Program

C++ code must be compiled into machine code before it can be executed. The process of compiling and running a C++ program involves several steps, but most modern IDEs streamline this for you.

  1. Terminal: If you prefer to use the terminal or command line, you can manually compile and run the program using the following steps:
  2. Save Your C++ File: Save your file with the .cpp extension. For example hello.cpp
  3. Open Terminal/Command Prompt: Navigate to the directory where your hello.cpp file is saved.
  4. Compile the Program: Use the following command to compile the program: g++ -o OBJECT_FILENAME SOURCE_FILENAME .cpp
  • Windows (MinGW) or Linux/macOS (GCC): g++ -o hello hello.cpp
  • Windows (MSVC): cl hello.cpp The -o hello flag tells the compiler to output an executable file named helllo
  1. Run the Executable: After compiling, you can run the program:
  • Windows: hello.exe
  • macOS/Linux: ./hello
  1. IDE: If you’re using an IDE like VSCode or CLion, the process is even simpler, as the IDE handles most of the compilation steps for you.
  • Compiling and Running in VSCode: In VSCode, open the hello.cpp file and click on the Run button (if you’ve installed the Code Runnerextension) or open the terminal within VSCode and use the g++ command as shown above.
  • Compiling and Running in CLion: CLion automatically compiles your project. Simply click the Run button at the top, and CLion will compile and execute the program for you. The output will appear in the IDE’s built-in console.

Starting C++ program

The basic structure of a C++ program revolves around several factors. A basic structure of a C++ program is: int main() { return 0; } Let's break down all the pieces of the code

  • int main() { ... }: serves as the entry point where the operating system starts executing the code. Every C++ program needs that. Whatever logic we will implement, this will be done inside the main() function.
  • return 0; : return statement in main() sends a status code (an integer number) back to the operating system for signaling how the program ended based on its value. Since the main function return an integer number, before the main function is specified the "int" type. An exit code of 0 generally indicates success, while any non-zero value signals some form of error. In this case, we did not programmed anything. Infact, if you try to run this code, nothing happen. This information is the starting point for any program in C++. Although some of it sounds strange, later, as we move on with the topics, it will be explained in detail why it all.

Variable names

C++ applies some specific rules and guidelines for naming variables. These rules ensure that variable names are valid and avoid conflicts with reserved words or other constructs used by the programming language. Rules for Naming Variables are:

  • Allowed Characters: Variable names can consist of letters (a-z, A-Z), digits (0-9), and underscores (). The first character of a variable name must be a letter or an underscore (), but not a digit.
  • Case Sensitivity: C++ variable names are case-sensitive, meaning upper and lower case letters are treated as different letters.
  • Reserved Keywords: You cannot use C++ reserved keywords as variable names (e.g. int, class, if, while, etc.).
  • No Spaces: Variable names cannot contain spaces.
  • Length of Name: There is no fixed limit on the length of a variable name, but in practice, long names should be avoided to keep the code readable.
  • No Special Characters: Special characters (e.g. @, #, %, &, etc.) are not allowed in variable names, except for the underscore (_) as altready mentioned. Examples of valid variable names: age total_amount myVar _counter my_variable Examples of invalid variable names: 3age (starts with a number) total#amount (contains a special character) int (reserved keyword) my variable (contains a space)

Comments

Comments are lines or blocks of text in the code that are ignored by the compiler. They are used to explain the code, document its functionality, or temporarily disable code during development. C++ supports two types of comments:

  • Single-line comments: These start with "//" and continue to the end of the line. // This is a single-line comment
  • Multi-line comments: These start with "/" and end with "/", and can span multiple lines. /* This is a multi-line comment */

Assignment Assignment refers to the process of assigning a value to a variable. We refere to assignment when the variable is already declared. This can happens when a variable change its stored value during the program logic. The syntax for assignment is: VARIABLE_NAME = VALUE ; It involves using the assignment operator, which is typically the equals sign (=), to store a value in a variable. The value on the right side of the equals sign is assigned to the variable on the left side. For example: int number; number = 42; float temperature; temperature = 36.5; double pi; pi = 3.14159; char grade; grade = 'A'; bool passed; passed = true;

Initialization When you initialize a variable, you assign it an initial value at the time of declaration. This is important because using an uninitialized variable can lead to undefined behavior, as it may contain garbage values left in memory. The syntax is: DATA_TYPE VARIABLE_NAME = VALUE ; or in case of more initialization: DATA_TYPE VARIABLE_NAME1 = VALUE1, VARIABLE_NAME2 = VALUE2 ; It works exactly like the assignment. For example: int number = 42; float temperature = 36.5; double pi = 3.14159; char grade = 'A'; bool passed = true; Memory cell with the variable name now store Value the assigned value. &

Memory

In C++, program memory is divided into several distinct regions, each with a specific purpose and behavior. Understanding these memory areas can help you write efficient and safe code, especially when working with dynamic memory allocation or managing variables with different lifetimes. The main areas of memory in a typical C++ program are:

  1. Stack
  2. Heap
  3. Static/Global
  4. Text We will see where every memory area is called. Let's start from the basic one:

Stack : The stack is a region of memory used for storing local variables, function parameters, return addresses, and function call information. It is managed automatically by the operating system in a Last-In, First-Out (LIFO) manner, which means that the last item added to the stack is the first one removed. The stack is automatically managed by the system. When a function is called (e.g. main()), memory for local variables and parameters is pushed onto the stack in a stack frame. When the function returns (e.g. return 0; in main()), its stack frame is popped off, and the memory is freed immediately. All the variables declared in our code are allocated on the stack when the code is compiled. Thus, during the execution all the necessary memory items will be ready to use. Large data structures can lead to stack overflow, where the program exceeds the stack’s allocated size and crashes. main(): Variables will be stacked one on top of the other

Text : is a read-only area of memory where the compiled machine code of the program is stored.

Pre-processor directives

Pre-processor directives are instructions that are executed by the pre-processor before the actual compilation of the code begins. These directives are commands that tell the compiler to preprocess the information before the code is compiled into machine language. Preprocessor directives are typically used to include external libraries, define constants, or perform conditional compilation, among other tasks. Pre-processor directives are identified by the "#" symbol at the beginning of the code, and they do not end with a semicolon. These commands are handled before the actual code is compiled and are not part of the C++ language itself—they are instructions to the preprocessor.

PREPROCESSOR_DIRECTIVE

Importing libraries

C++ is supported by a variety of ready-to-use functionalities called libraries: a set of tools and functionalities that were already written and they are ready to be recalled and used. This process have to be done before the compiling process starts. For this reason, exist a specific preprocessor directive used for this purpose. When you use "#include", the preprocessor literally copies the entire content of the specified file or library into your program at the point where the #include directive appears. This makes the specified content available for use in your code. Standard C++ libraries can be imported with: #include < LIBRARY_NAME> Example: #include // Includes the standard input/output library int main() { return 0; } In this example, the #include directive imports the input/output stream library

Stream Buffering

Streams in C++ are buffered, meaning that data sent through cout doesn’t always appear on the screen immediately. Instead, it is stored in a buffer and then flushed (i.e. transferred to the console) when the buffer is full or when a special command is encountered:

  • std::flush: Can be used to manually flush the buffer. Example: #include int main() { std::cout << "Hello, World!" << std::flush; return 0; } Buffer: Hello, World! Console: Hello, World!
  • std::endl: inserts a newline character (any following output will be written on a new line) but also flushes the output buffer. Example: #include int main() { std::cout << "Hello," << std::endl; std::cout << "World!"; return 0; } Buffer: Hello, Console: Hello, Buffer: World! Console: World! The final output will be: Hello, World! This functions ensures that any pending output is immediately written to the console. This buffering improves efficiency by minimizing the number of direct interactions with the system hardware.

cin: The cin object is the standard input stream in C++. It is used to read input from the user. The name cin stands for "character input," and like cout, it is part of the std namespace. std::cin >> VARIABLE ; where:

  • "std::" is the standard library prefix.
  • The ">>" operator is called the extraction operator, and it extracts (reads) data from the input stream and assigns it to the specified variable. Example: #include int main() { int age; std::cout << "Enter your age: "; std::cin >> age; std::cout << "You entered: " << age << std::endl; return 0; } The user is prompted to enter their age, and after the input is entered, the program displays it using cout: int age; std::cin >> age; std::cout << "You entered: " << age << std::endl; Buffer: You entered: 25 Console: You entered: 25 The cin object reads formatted input, meaning it interprets the data based on the type of the variable. For example, if you use cin to read into an integer variable, it will expect an integer input from the user. If the user enters something incompatible (like a letter instead of a number), the input operation may fail.

To access entities within the standard namespace, you have to specify the "std" prefix: std:: ELEMENT We can bring the entire namespace into scope with: using namespace std; For example, we can avoid to use every time the standard prefix "std::": #include using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; cout << "You entered: " << age << endl; return 0; }

Qualifiers

In C++, a qualifier is a keyword or modifier that is used to change the meaning or behavior of a variable, function, or type. Qualifiers provide additional information about how data can be accessed, modified, or used. The general declaration structure became: QUALIFIERS MODIFIER DATA_TYPE VARIABLE_NAME ; There are different kinds of qualifiers in C++ that serve specific purposes. They will be showed at the right moment.

Const

In C++ we can declare a constant variable, meaning that once a value is assigned, it cannot be changed. This is especially useful when you want to ensure certain values remain fixed, helping prevent accidental modifications. This can be accomplished in two ways:

  • const qualifier: The syntax for declaring a constant is: const DATA_TYPE VARIABLE_NAME ; Example: const float pi = 3.14; In this example, pi is a constant float with the value 3.14. Once it has been assigned, any attempt to modify it later in the program will result in an error. pi = 10; // You cannot modify a constant variable.
  • define preprocessor directive: The syntax for defining a constant is: #define VARIABLE_NAME VALUE Example: #define PI 3. The #define directive allows you to create macros, which are essentially placeholders that the preprocessor will replace with a specified value throughout the code before compilation rather than being treated as a variable. Since the replacement is done before compilation, the preprocessor does not enforce type checks like the compiler would for any variable (e.g. as it is done with the cin). For example, if you define #define PI 3.14 and use it in an integer context, there will be no warnings, but it should since a float is not an integer.