C ++ Study Notes-changing const
// Const and basic data type // const and pointer type # include
Using namespace std; int main () {const int x = 10; // x = 20; an error is returned here !!! Changing the value of const cannot return 0;} int main () {// 1. const int * p = NULL; equivalent to int const * p = NULL int x = 3, y = 4; const int * p = & x; p = & y; // here it is correct // * p = 4; here it is incorrect // 2.int * const p = NULL; int * const p = & x; // p = & y; here error // 3, const int * cont p = NULL; const int * const p = & x; // return 0 that cannot be changed here ;}
Example:
#include
using namespace std;int main(){const int x = 3;x = 5;int x = 3;const int y = x;y = 5;int x = 3;const int * y = &x;*y = 5;int x = 3, z = 4;int *const y = &x;y = &z;const int x = 3;const int &y = x;y = &z;return 0;}
Result
For details, see the error message:
The Code is as follows:
#include
using namespace std;int main(){const int x = 3;x = 5;return 0;}
Result:
# Include
Using namespace std; int main () {int x = 2; int y = 5; int const * p = & x; cout <* p <
# Include
Using namespace std; int main () {int x = 2; int y = 5; int const & z = x; z = 10; // error x = 11 will be reported; return 0 ;}
// Use const for the function
// The function uses const # include
Using namespace std; void fun (int & a, int & B) {a = 10; B = 22 ;} // The function is faulty. // The value cannot be assigned./* void fun1 (const int & a, const int & B) {a = 33; B = 44;} */int main () {int x = 2; int y = 5; fun (x, y); cout <the result of the function without const modifier is: <x <, <y <
If the comments of the preceding code are removed, the following error message is displayed: