Swapping integers, pass by const ref: is it possible?

I am trying to go over the exercises in the book by Duffy, Intro to C++ for Fin. Eng.

In chapter 6 he asks to write code for a function that swaps two arguments passed by constant reference, void swap(const int& x, const int& y) ?

Is this at all possible?? My newbie intuition says no, if the objects are constant, the function can not modify them. Thanks!
No, since like you said, they are not modifiable (unless you const_cast or hack around it with pointers or something).
This is a problem for other languages as well. It's solvable, so keep thinking.
Last edited on
choisum, why would he want to solve it?
I guess OP is reading the book to learn something. OP can jump in here...
Thanks everyone for the replies.

Firedraco: can you expand on how you would do it with const_cast? (I can't figure that out from the top of my head.)
It's all very fishy. Since the book is about Financial Engineering, rather than how to hack C++ into doing stuff you should not be doing....
did the book mean const function? void swap(int&, int&) const ??
+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);
Note that the following works (at least for me but I don't find a reason why not universally):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <cstdlib>
#include <iostream>
#include <stdio.h>
using namespace std;

void swap(const int & ca, const int & 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)
Last edited on
Topic archived. No new replies allowed.