+1 firedraco, +1 to choisum's "stuff you should not be doing"
This function is ill formed and instead of trying to trick C++ into making it work, it really should be corrected to take non-const parameters.
Makes me wonder why this problem is appearing in a C++ book for beginners. I can't imagine what a beginner can learn from this other than how to write terrible code. Then again I'm often suprised by "professional" books.
Casting a const T & to a T & has undefined behavior for all operations performed on the latter. Maybe nothing will happen, or maybe something catastrophic will.
To give an example, a function void swap(const int &,const int &) would let you call it this way: swap(1,2);
#include <cstdlib>
#include <iostream>
#include <stdio.h>
usingnamespace std;
void swap(constint & ca, constint & cb)
{
int & a=const_cast<int&>(ca);
int & b=const_cast<int&>(cb);
int temp=a;
a=b;
b=temp;
}
int main()
{
int a=10;
int b=20;
printf("a is %d and b is %d\n",a,b);
swap(a,b);
printf("a is %d and b is %d\n",a,b);
system("pause");
return 0;
}
However, if I declare a and b as constants in main it won't work (it compiles and runs but the values are not swapped)