Book Image

C++ Fundamentals

By : Antonio Mallia, Francesco Zoffoli
Book Image

C++ Fundamentals

By: Antonio Mallia, Francesco Zoffoli

Overview of this book

C++ Fundamentals begins by introducing you to the C++ compilation model and syntax. You will then study data types, variable declaration, scope, and control flow statements. With the help of this book, you'll be able to compile fully working C++ code and understand how variables, references, and pointers can be used to manipulate the state of the program. Next, you will explore functions and classes — the features that C++ offers to organize a program — and use them to solve more complex problems. You will also understand common pitfalls and modern best practices, especially the ones that diverge from the C++98 guidelines. As you advance through the chapters, you'll study the advantages of generic programming and write your own templates to make generic algorithms that work with any type. This C++ book will guide you in fully exploiting standard containers and algorithms, understanding how to pick the appropriate one for each problem. By the end of this book, you will not only be able to write efficient code but also be equipped to improve the readability, performance, and maintainability of your programs.
Table of Contents (9 chapters)
C++ Fundamentals
Preface

Arrays


An array is a data structure containing a series of elements of the same type that have been placed in contiguous memory locations that can be individually accessed by their position.

Arrays have fixed sizes and cannot be extended; this contributes to their runtime performance, with a cost in terms of limited flexibility.

Array Declaration

Like any other variable, arrays need to be declared before they can be used. An array declaration has the following form:

type name [elements];

Here, type is the type of the contained elements, name is the identifier of the array variable, and elements is the length of the array, so it signifies the number of elements contained within.

The term elements needs to be a constant expressions that is known at compile time, since that is the time when the array size is evaluated to determine the dimension of the block of static memory to allocate.

When an array is declared, its content is left undetermined, which means that the elements are not set to any specific value. This is often confusing for programmers as you might expect that the elements are initialized to the default value for the array type.

Array Initialization

Array elements can be specifically initialized at declaration time by enclosing these initial values in braces:

int foo [5] = { 1, 2, 11, 15, 1989 };

When we initialize a list array, we can also omit its length as it will be determined by the number of values provided. The following declaration is equivalent to the previous one:

int foo [] = { 1, 2, 11, 15, 1989 };

If the number of elements is provided, but the array is initialized with fewer elements, then the remaining value will be zero-initialized, for example:

int foo [5] = { 1, 2, 11 };

The previous code is equivalent to the following:

int foo [5] = { 1, 2, 11, 0, 0 };

Accessing the Values of an Array

The values of an array can be accessed in the same way as any other values of the same type. The following is the syntax to access an array:

name[index]

An element of an array can be accessed to store a new element or to read its value.

For example, the following statement updates the value at position 4 of the previously declared array named foo:

foo [4] = 15

The following is used to copy the content of the element at position 2 into a new variable:

int x = foo [2]

It is important to notice that the elements at positions 4 and 2 refer to the fifth and third elements, respectively. This is due to the fact that indexing starts from 0. The following diagram illustrates how index entries work in arrays:

Figure 1.9: Initializing a one-dimensional array

Exceeding the valid range of indices for an array is syntactically correct, so the compiler will not produce any errors. Accessing an array out of bounds in C++ is considered an undefined behavior, which means that the code's behavior is not prescribed by the language specification. This can result in runtime errors such as bugs caused by access to an unallocated location in memory or program termination (segmentation fault) due to an attempt to access memory not owned by the program.

Multidimensional Arrays

Multidimensional arrays are commonly described as arrays of arrays, where an array's elements are other arrays.

The following syntax illustrates a bi-dimensional array:

type name [n][m];
int bi_array [3][4]

Here, n is the dimension of the array and m is the dimension of its elements.

Typically, in a bi-dimensional array like the previous one, the first dimension is referred to as the row and the second one is referred to as the column.

Multidimensional arrays are not limited to two dimensions; they can have as many dimensions as needed, but keep in mind that the memory that's used increases exponentially with each dimension. Similar to one-dimensional arrays, multidimensional arrays can be initialized by specifying a list of initializers, one for each row. Let's examine the following code:

#include <iostream>
int main()
{
  int foo [3][5] = {{ 1, 2, 11, 15, 1989 }, { 0, 7, 1, 5, 19 }, { 9, 6, 131, 1, 2 }};
  for (int x = 0; x < 3; x++) 
  { 
    for (int y = 0; y < 5; y++) 
    {
      std::cout <<"Array element at [" << x << "]" << "[" << y << "]: "<< foo[x][y] << std::endl;
    }
  }
}
Output:
Array element at [0][0]: 1
Array element at [0][1]: 2
Array element at [0][2]: 11
Array element at [0][3]: 15
Array element at [0][4]: 1989
Array element at [1][0]: 0
Array element at [1][1]: 7
Array element at [1][2]: 1
Array element at [1][3]: 5
Array element at [1][4]: 19
Array element at [2][0]: 9
Array element at [2][1]: 6
Array element at [2][2]: 131
Array element at [2][3]: 1
Array element at [2][4]: 2

Alternatively, since the compiler can infer the length of the internal arrays from the definition, the nested braces are optional and provided only for readability:

int foo [3][5] = {1, 2, 11, 15, 1989, 0, 7, 1, 5, 19, 9, 6, 131, 1, 2};

Activity 2: Defining a Bi-Dimensional Array and Initializing Its Elements

In this section, we will define a bi-dimensional array (3x3) of type integer and write a program to assign each element the addition of their corresponding index entries in the array:

  1. Define an array of integers of size 3x3.

  2. Iterate over each element of the array using a nested for loop and assign the product values x and y to the index.

Note

The solution for this activity can be found on page 282.