const and pointers

Basic types / Pointers

//const on the right side of * locks the pointer,
//on the left side it locks the value
int a = 1;
int b = 2;

//a pointer to const: no change of the value through it
const int *pValue = &a;
//*pValue = 10; //<-Error
pValue = &b;
//*pValue is 2

//a const pointer: it can't point to another variable
int *const pFixed = &a;
*pFixed = 10;
//pFixed = &b; //<-Error
//a is 10

//both are locked
const int *const pBoth = &b;
//*pBoth is 2
//*pBoth = 20; //<-Error
//pBoth = &a; //<-Error

//const in a parameter: the function promises to only read
int sum(const int *numbers, size_t count) {
    int total = 0;
    for (size_t i = 0; i < count; i++) {
        total += numbers[i];
    }
    return total;
}

int numbers[] = {1, 2, 3};
int total = sum(numbers, 3);
//total is 6

printf("*pValue is %d\n", *pValue);
printf("a is %d\n", a);
printf("*pBoth is %d\n", *pBoth);
printf("total is %d\n", total);