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

Apr 6, 2010 at 11:58pm
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!
Apr 7, 2010 at 12:18am
No, since like you said, they are not modifiable (unless you const_cast or hack around it with pointers or something).
Apr 7, 2010 at 12:36am
This is a problem for other languages as well. It's solvable, so keep thinking.
Last edited on Apr 7, 2010 at 12:36am
Apr 7, 2010 at 12:54am
choisum, why would he want to solve it?
Apr 7, 2010 at 1:05am
I guess OP is reading the book to learn something. OP can jump in here...
Apr 7, 2010 at 12:11pm
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.)
Apr 7, 2010 at 12:19pm
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....
Apr 7, 2010 at 12:50pm
did the book mean const function? void swap(int&, int&) const ??
Apr 7, 2010 at 2:55pm
+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.
Apr 7, 2010 at 3:26pm
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);
Apr 7, 2010 at 6:25pm
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 Apr 7, 2010 at 7:12pm
Topic archived. No new replies allowed.