summaryrefslogtreecommitdiffstats
path: root/references.cpp
blob: be40a5041177e98672dd111d07ca866f23dad9d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>

// a basic new feature of C++ are references, they are like
// pointers, but they *can't* be null, which btw in c++ is `nullptr'


// here is a typical C example to use pointers
void inc_ptr_val(int *v) {
    // check that v is not null
    if (v == nullptr) {
        return;
    }

    // increment where v points
    (*v)++;
}

// and here is a new (better) version
void inc_ref_val(int& v) {
    // no need to check
    // no need to dereference
    v++;
}

// an interesting twist is that we can now have const references
// which is like a C "T const * const" ie read only reference
// and is used to not copy big things on the stack
bool is_hello(const std::string& s) {
    // s cannot be changed, only read
    return s == "hello";
}


int main(int argc, char *arg[]) {

    int hello = 10;
    std::cout << hello << std::endl;

    inc_ptr_val(&hello);
    std::cout << hello << std::endl;

    inc_ref_val(hello);
    std::cout << hello << std::endl;
}