c++

const -> pointer

Const was used with Pointer.

  • The first case:

    The address which Pointer contained is a Constant, Can’t be changed, but you can change the Data pointed to:

    1
    2
    3
    4
    5
    int daysInMonth = 30;
    int * const pDaysInMonth = &daysInMonth;
    *pDaysInMonth = 31; //This is ok, Data pointed to can be changed
    int daysInLunarMonth = 28;
    pDaysInMonth = &daysInLunarMonth; //This is shit, Cannot change address!
  • The second cace:

    Data pointed to is Constant, can’t be changed, but you can change the address which Pointer contained, and that means the Pointer can pointer to another variable:

    1
    2
    3
    4
    5
    6
    int hoursInday = 24;
    const int* pointsToInt = &housday;
    int mouthInYear = 12;
    pointsToInt = &monthsInYear;
    *pointsToInt = 13; //Not OK! Cannot change data being pointed to
    int* newPointer = pointsToInt; //Not OK! cannot assign const to non-const
  • The third cace:

    Both Address that Pointer contains and Variable It pointer to is Constant, cannot be changed.(which is the most rigorous)

    1
    2
    3
    4
    5
    int hoursInDay = 24;
    const int* const pHousInDay = &hoursInDay;
    *pHoursInDay = 25; //Not OK! Cannot change data being pointed to
    int daysInMonth = 30;
    pHoursInDay = &daysInMonth; //Not OK! Cannot change address

Pass the pointer to the function.

When a pointer was used as a function argument, it’s important that Function only can change arguments that you hope to change.For example, when you passed a radius to calculate area of a circle, it can’t be changed. YOU CAN USE CONST.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void CalcArea(const double* const ptrPi, const double* const ptrRadius, double* const ptr Area)//const pointer to const data, no changes allowed, can change data pointed to
{
if(ptrPi && ptrRadius && ptrArea)
*ptrArea = (*ptrPi) * (*ptrRadius) * (*ptrRadius);
//Pay attention to Product sign 'x' and indirect operater '*'
}

int main(){
const double Pi = 3.14159265358979323846;
double radius = 0;
cin >> radius;

double area = 0;
CalcArea (&Pi, &radius, &area);
//only area can be changed in func;
return 0;
}
Share