I'm currently trying to learn some C++ and came across following unintuitive behavior. As t is a pointer to a const int I would expect *t to stay the same as long as we do not change t.
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int a = 3;
const int* t = &a; //Why is this allowed? a is NOT const int
a = 4;
cout << *t << endl; //This does then print 4
//*t = 4; //Throws error.
return 0;
}
Can anyone explain why this is does compile?
int a = 1; const int b = a;is just fine, and nowbis const whileais not, even if the hold the same valuebreceives a copy of the value ofa.int a = 1; const int& b = a;nowbis a reference forb, but you cannot change the value throughbeven ifais not constvoid foo(const T&)this just means, that inside the function, the value cannot change, but the parameter passed to the function is not necessarilyconst