C ++ int const and const int difference

  1. If the object is not against, there is no difference
int const x = 3;
const int x = 3;
  1. If the object is a pointer, they are different
    int* const p = &array: p is not able to point to other pointers Address
    const int* p = &array: Pointer p read-only &array, can not be modified

For example,

#include <iostream>
 
using namespace std;

int main()
{
    int arr[3]={1,2,3};
    int varr[3]={100,200,300};
    const int* p1 = arr;
    int* const p2 = arr;

    cout << *p1 << endl;
    cout << *p2 << endl;

    // *p1 = 22; // error
    *p2 = 22;
    cout << *p2 << endl;
    cout << arr[0] << endl;

    p1 = varr;
    cout << *p1 << endl;

    p2 = varr;//error
    return 0;
}

Guess you like

Origin www.cnblogs.com/yaos/p/12099521.html