C / C++
Interesting Topics
const: It is a promise by the programmer to the compiler, saying that “I won’t change the value of this variable, after I initialize it”
If the promise is break then, the compiler won’t compile the program.
The below code will compile and works, even though it is changing the value of *ptr, because there is NO “const“:
#include <iostream>
using namespace std;
int main()
{
int *ptr;
int i = 50;
ptr = &i;
cout << "Value at ptr : " << *ptr << endl;
*ptr = 100;
cout << "Value at ptr : " << *ptr << endl;
return 0;
}
The below code doesn’t compile, because *ptr is declared as a “const” and trying to change it after initialization:
#include <iostream>
using namespace std;
int main()
{
const int *ptr;
int i = 50;
ptr = &i;
cout << "Value at ptr : " << *ptr << endl;
*ptr = 100;
cout << "Value at ptr : " << *ptr << endl;
return 0;
}
Compiler will throw the below compilation error:
qualifiers.cpp:14:10: error: read-only variable is not assignable
*ptr = 100;
~~~~ ^
1 error generated.
“As simple as that.”