Section 2

<- View full list of my projects

Things to remember (i.e. notes to self)

Unless explicitly stated, calculations will default to converting the solution to unsigned, unless both operands are signed. If one operand is signed (and is negative) and the other is unsigned (and is positive) the solution will be unsigned (i.e. 2^16-1 or whatever).

If you allocate an input number (x) to an unsigned representation that is out of the representations range (e.g. it is negative), the number stored will be ‘x mod [range of representation]’.

The range of possible values for an unsigned 32bit int is 0 through to 4294967295.  This is because the largest value occurs at 1111….111 (32 1’s) which is 1 less than 2^32 (which is 4294967296).

A variable is a literal when it’s value is self evident, i.e. an integer.

A decimal literal will be stored as either an int, long or long long (the smallest that it will fit in). The same applies to Octal and Hexadecimal, except they can sometimes also be stored in the unsigned versions by default. Suffixes can be used to control which one is used. Shorts are never used. Remember, literal integers are stored without the minus sign (this is an operator). Floating points use the type double by default. Again, suffixes can be used to override. Another useful suffix is the U, which indicates a literal is stored unsigned.

A single letter between single quotation marks is a char literal. E.g. ‘a’. This is different to a string literal, which is an array of chars, ending with a blank char (which uses extra memory), e.g. “hello”. Note the use of double quotes for a string. This is stored as [‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’]. Two strings placed adjacently (or with a separator character like tab, line break or comma) will be concatenated.

Special characters such as newline, tab, backspace and character representations using ASCII codes can be produced using escape codes, i.e. a backslash (\) followed by a letter or number (either ‘x’ followed by Hexadecimal representation, or Octal representation (<= 3 digits)). See Section 2.1 in the book for the list.

Exercise 2.1

Part 1: Ints have minimum length 16 bit, long 32bit, long long 64bit and short has minimum length 16bit (just like int). In practice however, int and long have the same length, and short is too small to be useful. Long long is only used when very large numbers are been processed / stored.
Part 2: In a signed type, the first bit is used to determine if the value is negative (1) or positive (0). If the type is signed, the range of possible values that can be held is shifted such that the size of the range of possible values beneath zero is exactly one more than the size of the range of possible values above zero.
Part 3: A double has more precision than a float, and the extra cost of processing is not large enough to push us away from using it as the normal type for floating point data.

Exercise 2.2

The rate will be a percentage, which may be a decimal. So we will use a double.
The principal (amount borred from the lender minus the amount paid back to the lender) may have pence (or cents if you are not British) – these represent decimals, so we would use a double. N.B. – there is an alternative – we could hold a measure of pennies (or cents) instead of Pounds (or dollars), meaning we could hold the entire amount as an int (or long long if we were borrowing a lot!). Payment is again an amount of money, so we would apply the same as we did for principal.

Exercise 2.3

  1. 32
  2. 4294967265
  3. 32
  4. -32
  5. 0
  6. 0

Exercise 2.4

int main() {
    unsigned u = 10, u2 = 42;
    int i = 10, i2 = 42;
    std::cout << u2 - u << std::endl;
    std::cout << u - u2 << std::endl;
    std::cout << i2 - i << std::endl;
    std::cout << i - i2 << std::endl;
    std::cout << i - u << std::endl;
    std::cout << u - i << std::endl;
    return 0;
}

Exercise 2.5

Question A

'a'

is a literal character.

L'a'

is a literal wide character.

"a"

is a literal string containing only the char ‘a’ and a null character.

'a'

as in the last part, except that the chars are stored as wide characters.

Question B

10
is a literal signed int.

10u

is literal unsigned int.

10L

is a signed literal long.

10uL

is an unsigned literal long.

012

is either a signed or unsigned Octal int.

0xC

is either a signed or unsigned Hexadecimal int.

Question C

3.14

is a signed double.

3.14f

is a signed float.

3.14L

is a signed long double.

Question D

10
is a signed int.

10u

is an unsigned int.

10.

is an unsigned double.

10e-2

is an unsigned double representing 0.1

Exercise 2.6

In the second definition, we define the values with a zero in-front of them, indicating that the values are in Octal format (base 8). In this case, the values are equal (7 = 07), but in other cases this is not true (15 != 015).
In addition, the second definition will not execute. For base 8, each digit must be in the inclusive range of 0 to 7. There is a 9, which is not a valid character in base 8, so the compiler will throw an error.

Exercise 2.7

Question A

\145 is e
\012 is \n (newline)
So, the value is a string with contents: Who goes with Fergus? [followed by newline].
The type is a string literal.

Question B

e1 means x10.
So, value is 31.4
The type is a long double.

Question C

1024f has value 1024.
The f indicates that the type is a float.

Question D

3.14L has value 3.14.
The L indicates that it has type long double.

Exercise 2.8

Part 1:

int main() {
    std::cout << "\62\115" << std::endl;
    return 0;

}

Part 2:

int main() {
    std::cout << "\62\t\115\n" << std::endl;
    return 0;
}

Intermediate Note

At this point, I am going to switch to using printf for outputs, as there’s less code for it. First you need to ‘import at the top of your file, then just use printf(‘Hello, World!’) in your code. For another example, see Exercise 2.17.

Exercise 2.9

Question A

Can not make declaration of int in cin.  Compiler expects to just assign input_value, not declare it then assign it.

Question B

Will return error as int can not hold decimal points, so some data is truncated.

Question C

Three term assignment illegal. Must do:

double salary = 9999.99;
double wage = salary;

Question D

Not illegal, however value stored in i will be ‘3’, not ‘3.14’.

Exercise 2.10

global_str is initialised to empty string.
global_int is initialised to 0.
local_int is uninitialised (error raised if attempt to access made).
local_str is uninitialised (error raised if attempt to access made).

Exercise 2.11

Question A

Overrides external definition of ix, so defines new ix as 1024.

Question B

Definition.

Question C

Declaration (‘extern’ keyword indicates it exists elsewhere, and we are using the variable defined elsewhere).

Exercise 2.12

A Invalid – double is keyword.
B Valid
C Invalid – hyphen not allowed in variable name – use underscore.
D Invalid – variable names must begin with letter or underscore.
E Valid

Exercise 2.13

j = 100

Exercise 2.14

Program is illegal, as curly braces { and } are missing to mark the beginning and end of the for loop. If this were a typo in the book and there were there, the values printed would be:

10 45

Exercise 2.15

A. Valid, but 1.01 will be truncated to 1.
B. Invalid, can not make reference to literal.
C. Valid
D. Invalid, reference must be initialised.

Exercise 2.16

A. Valid – sets ‘d’ (type ‘double’) to ‘3.14159’.
B. Valid – sets ‘d’ (type ‘double’) to 0.
C. Valid – sets ‘i’ to the truncated int value of d (0 in this case).
D. Valid – sets ‘i’ to the truncated int value of d (0 in this case).

Exercise 2.17

10 10

If you you want to test the code for this, use:

int main() {
    int i, &ri = i;
    i = 5, ri = 10;
    printf("%i %i", i, ri);
}

Exercise 2.18

Changes the value of the object that is pointed to by the pointer:

int main() {
    // Expect output to first reflect the default value of 7, then to reflect
    // the value changed via the pointer (of 6).
    int myInt = 7, *pointerToMyInt = &myInt;
    printf("%i\n", myInt);
    *pointerToMyInt = 6;
    printf("%i\n", myInt);
}

Changes the object that the pointer points to (so it points to a different object):

int main() {
    // Will first print the contents of objectToPointTo1, then we switch the
    // pointer to point to objectToPointTo2,  whose value we then print.
    // Expected result: '1020'.
    int objectToPointTo1 = 10, objectToPointTo2 = 20,
    *ourPointer = &objectToPointTo1;
    printf("%i\n", *ourPointer);
    ourPointer = &objectToPointTo2;
    printf("%i\n", *ourPointer);
}

Exercise 2.19

A pointer is a distinct object, whereas a reference is just an alternative name for an object.
Pointers can be uninitialised when first declared, whereas references can not be.
References are static – they can not be re-assigned to refer to a different object, whereas pointers can have the address they point to adjusted.

Exercise 2.20

  1. Defines an int called i, with initial value 42.
  2. Creates a pointer p1 that points to i.
  3. Sets i to the value of i^2 via dereferencing the pointer.

Exercise 2.21

A. Illegal – can not assign an int pointer to double.
B. Illegal – trying to assign pointer to point to the memory address specified by the contents of an int.
C. Legal.

Exercise 2.22

if (p) // ...

If pointer is not a nullptr (doesn’t point to address 0), return true and enter if block.

if (*p) // ...

If int that is pointed to by p is not zero, return true and enter if block.

Exercise 2.23

No, it’s not possible to determine if a pointer points to valid object.  Take the following example:

int mi = 7;
int *mp1 = &mi, *mp2 = mp1;
delete mp1;
mp1 = nullptr;

The delete keyword frees the memory pointed to by mp1, and then because the pointer now points to memory of unknown content, we point the pointer to nullptr for safety. The problem is that this has no effect on mp2, which was a clone of mp1. mp2 is now invalid as the memory it points to has been deleted, so dereferencing it would result in undefined behaviour.

Exercise 2.24

Because void pointers can hold data of any type (e.g. an int), whereas pointers of type long can only point to objects of type long. Trying to point a pointer of type long to a non-long-type object is illegal.