Study notes: Fundamentals of C++

| updated

Notes from the edX course Fundamentals of C++ by IBM

high-level:

comments: // ... or /* ... */

identifiers:

keywords: 32 in C++ and C, plus 30 more only in C++

variable: location in memory where value is stored. Must be declared before use.

program structure:

example:

#include <iostream>
using namespace std;
int main() {
  cout << "Hello" << endl;
  return 0;
}

compilation:

program.cpp —[ preprocessor ]→ pure cpp file without pp directives —[ compiler ]→ object file —[ linker ]→ library or executable

Data types

Compiler produces instruction for allocator to allocate memory for a variable based on its type:

object (constant or variable): identifier (name), memory address, type

Data type modifiers (qualifiers) affect the size of primitive (built-in) types – unsigned, short, long. (Resulting size depends on the arch compiled for.)

Constants

Allowed in header files.

Const pointer cannot be assigned to a normal pointer. (But those defined via preprocessor directives can.)

Literals (incl. strings) are constants.

Strings

Class from the stdlib.

Usage:

#include <string>;
std::string s = "a string";

Functions for C-style strings (0-terminated): strcpy, strlen, etc.

Qualifiers (data type modifiers)

Basic I/O

Example using stdout:

std::cout << "str" << std::endl;
int x = 1;
cout << x;

Example using stdin:

int x;
std::cin >> x;

Works for char, int, string … other data types?

Type conversion

Implicit: smaller object assigned to larger. Automatic conversion done by the compiler. e.g.

char c = 'a';
int i = c;
double d = i;

Explicit (casting): larger → smaller – potential data loss e.g.

double d;
d = 1.5;
int i = d;  // invalid
int i = (int)d;

Operators

Symbols for maths/logic operations:

also:

Precedence: * binds more strongly than + etc.

Associativity: order of application for operators of the same precedence. E.g. 100 / 2 * 10 => 500. / and * are both applied left-to-right.