#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
void f(int& a)
{
a++;
cout<<a<<"\n";
}
int main()
{
const int c=7;
f(const_cast<int&>(c));
cout<<c<<"\n";
int& b=const_cast<int&>(c);
b++;
const int& t=c;
cout<<t;
cout<<b<<"\n"<<c;
}`
Please explain the output i am getting:-
8
7
99
7
Okay, I hope you are aware of how const_cast<> works. As you can see in your code above, the typecasting has been done to a reference variable(int&). Thus, in the function call, you have passed the reference of c and thus the value of c can be modified. Flow:
a++;
cout<<a<<endl;// 8 gets printed here, since it is a reference, value can be modified
cout<<c<<endl;// you are outputting the value value of constant variable c
b is again assigned the reference to c, thus b=7 and &b is the memory location
b++; // b=9, because the value was modified by the a++ in function call, as in the reference, changes made inside the function are visible outside the call also.
t is assigned reference to c// thus t=9
cout<<t; gives 9
cout<<b<<"\n"<<c gives 9 in the same line of t which you see as 99(put spaces in ur code for clarity) and c is still 7( const variable)