C++ Primer ex 7.6

A

arnuld

can we make it better?


/* C++ Primer - 4/e
*
* exercise 7.6
* STATEMENT:
* write a funtion that swap vales pointed by two pointers to int.
*/

#include <iostream>

int swap_values(int* ip, int* jp)
{
int temp = *ip;
*ip = *jp;
*jp = temp;

return 0;
}


int main()
{
std::cout << "enter 2 integers: " << '\n';

std::cout << " i = ";
int i;
std::cin >> i;

std::cout << " j = ";
int j;
std::cin >> j;

int* ip = &i;
int* jp = &j;
swap_values( ip, jp );

std::cout << "values swapped: " << '\n'
<< " i = " << i
<< " j = " << j
<< std::endl;

return 0;
}

/* OUTPUT
[arnuld@arch cpp] $ ./a.out
enter 2 integers:
i = 3
j = 2
values swapped:
i = 2 j = 3
[arnuld@arch cpp] $ ./a.out
enter 2 integers:
i = -9
j = 0
values swapped:
i = 0 j = -9
[arnuld@arch cpp] $

*/
 
A

Alf P. Steinbach

* arnuld:
can we make it better?


/* C++ Primer - 4/e
*
* exercise 7.6
* STATEMENT:
* write a funtion that swap vales pointed by two pointers to int.
*/

#include <iostream>

int swap_values(int* ip, int* jp)
{
int temp = *ip;
*ip = *jp;
*jp = temp;

return 0;
}


int main()
{
std::cout << "enter 2 integers: " << '\n';

std::cout << " i = ";
int i;
std::cin >> i;

std::cout << " j = ";
int j;
std::cin >> j;

int* ip = &i;
int* jp = &j;
swap_values( ip, jp );

std::cout << "values swapped: " << '\n'
<< " i = " << i
<< " j = " << j
<< std::endl;

return 0;
}

Yes, you can (1) make those pointers point to const int, as you did in
previous exercise, and (2) implement the function in terms of std::swap.
 
F

Frank Birbacher

Hi!
* arnuld:
int swap_values(int* ip, int* jp)
[snip]
Yes, you can (1) make those pointers point to const int, as you did in
previous exercise,

No, you cannot. The swap function actually needs to modify the values in
order to swap them.
and (2) implement the function in terms of std::swap.

Which is hopefully what the excercise leads to after introducing references.

Frank
 
F

Frank Birbacher

Hi!
can we make it better?

Alf said something about "const" already. But you can only use it here:

int swap_values(int* const ip, int* const jp)
{
const int temp = *ip;
*ip = *jp;
*jp = temp;
}

Frank
 
F

Frank Birbacher

Hi!
#include <iostream> [snip]
std::cout << "enter 2 integers: " << '\n';

Theoretically you need "#include <ostream>" for this to work. <iostream>
only defines cout and cin, but not what "<<" means to them. <ostream>
defines "<<". For a long time I thought "iostream" would include both
"istream" and "ostream", but I had to learn they are completely
indepentant. What I assume is that "ostream" includes "istream". I think
I got that somewhere. So if you ever come along a compiler which refuses
to compile your code, then include <ostream> as well.

Frank
 
?

=?ISO-8859-15?Q?Erik_Wikstr=F6m?=

Hi!
#include <iostream> [snip]
std::cout << "enter 2 integers: " << '\n';

Theoretically you need "#include <ostream>" for this to work. <iostream>
only defines cout and cin, but not what "<<" means to them. <ostream>
defines "<<". For a long time I thought "iostream" would include both
"istream" and "ostream", but I had to learn they are completely
indepentant. What I assume is that "ostream" includes "istream". I think
I got that somewhere. So if you ever come along a compiler which refuses
to compile your code, then include <ostream> as well.

The draft of the next standard has been amended to better reflect
reality (i.e. you including <iostream> will include <(i|o)stream>) since
there's no implementation of consequence out there that does not allow
the OP's code.
 
H

HumbleWorker

can we make it better?

/* C++ Primer - 4/e
*
* exercise 7.6
* STATEMENT:
* write a funtion that swap vales pointed by two pointers to int.

COMMENTS OF HW:

This is more efficient:

void swap_values (int * const& iFirst, int * const& iSecond)
{
int iTemp = *iFirst;
*iFirst = *iSecond;
*iSecond = iTemp;

return;
}

int main(/*int argc, _TCHAR* argv[]*/)
{
int i, j;
std::cout << "Enter the two numbers: \ni = ";
std::cin >> i;
assert (std::cin);
std::cout << "j = ";
std::cin >> j;
assert (std::cin);

int* pi = &i;
int* pj = &j;
swap_values (pi, pj);

std::cout << "After swap, i = " << i << " j = " << j << std::endl;
return 0;
}


HW
 
P

Pete Becker

COMMENTS OF HW:

This is more efficient:

void swap_values (int * const& iFirst, int * const& iSecond)

For pointers it's very unlikely that passing by reference will be more
efficient than passing by value. It wil typically be slower, because
under the covers the code has to first dereference the pointer that
implements the reference, then dereference the resulting pointer to get
at the actual data; passing by value doesn't require that first step.
On the other hand, passing pointers by reference clutters the function
definition, reducing the efficiency of the programmer who has to write
the function and of every programmer who has to maintain it.
 
A

Alf P. Steinbach

* Frank Birbacher:
Hi!
* arnuld:
int swap_values(int* ip, int* jp)
[snip]
Yes, you can (1) make those pointers point to const int, as you did in
previous exercise,

No, you cannot. The swap function actually needs to modify the values in
order to swap them.

Yes, sorry.

Which is hopefully what the excercise leads to after introducing references.

Would you also forbid use of std::cout?
 
F

Frank Birbacher

Hi!
Would you also forbid use of std::cout?

No, because it's too complex for you to implement it as an excercise.
I'm not a teaching expert, but usually you go throught implementing
various "small" functions like std::max yourself before using the
predefined ones. So first implement my_max, then be told there is
std::max. Am I wrong here?

Frank
 
A

Alf P. Steinbach

* Frank Birbacher:
No, because it's too complex for you to implement it as an excercise.
I'm not a teaching expert, but usually you go throught implementing
various "small" functions like std::max yourself before using the
predefined ones. So first implement my_max, then be told there is
std::max. Am I wrong here?

Not necessarily, people learn in different ways.

But I've always found that students grasp things faster if examples
introduce one concept at a time (or as few as possible).

The question is whether this exercise is intended to teach use of
pointers, where swapping is just something to use them for, or whether
the exercise is intended to teach swapping, where pointers are just
incidental because references haven't been introduced yet.
 
H

HumbleWorker

COMMENTS OF HW: The subject of the question is a pointer, we have been
GIVEN two POINTERS the contents of which have to be swapped. The
pointers are GIVEN, so it is more appropriate to pass them by
reference and act on them. The point is very subtle.

Passing the pointers by value would be more appropriate if we were
using pointers as an intermediate helpers for swapping their contents.
In this case the pointers to ints are given to us as the starting
point.

The following would be a more appropriate demonstration of the fuction
swap_values()

int main(/*int argc, _TCHAR* argv[]*/)
{
// take any two pointers from the heap
// fill them with two values
int *i = new int (/*fill with say,*/50);
int *j = new int (/*fill with say,*/9);

std::cout << "Before swap the contents are, i = "
<< *i << " j = " << *j << std::endl;

// swap the values in the two pointers
swap_values (i, j);

std::cout << "After swap the contents are, i = "
<< *i << " j = " << *j << std::endl;

delete i;
delete j;
return 0;
}
because
under the covers the code has to first dereference the pointer that
implements the reference, then dereference the resulting pointer to get
at the actual data;

COMMENTS OF HW: I donot think an optimizing compliler would take that
roundabout path for implementing an int*&. Copying the contents of the
int*[ie the starting address of i or j] may be the approach taken.

On the other hand, passing pointers by reference clutters the function
definition, reducing the efficiency of the programmer who has to write
the function and of every programmer who has to maintain it

COMMENTS OF HW: This has always been a matter of opinion and taste,
but I think it is better to take the approach that maps to the
physical problem our code is solving. In this particular case passing
the pointers themselves by reference is closer to what our code is
trying to solve: write a funtion that swaps values pointed by two
pointers to int.
 
I

Ian Collins

HumbleWorker said:
COMMENTS OF HW: The subject of the question is a pointer, we have been
GIVEN two POINTERS the contents of which have to be swapped. The
pointers are GIVEN, so it is more appropriate to pass them by
reference and act on them. The point is very subtle.
No, it's silly. If you were given to integers to pass to a function,
would you pass reference to them?
Passing the pointers by value would be more appropriate if we were
using pointers as an intermediate helpers for swapping their contents.
In this case the pointers to ints are given to us as the starting
point.
Eh?

The following would be a more appropriate demonstration of the fuction
swap_values()
Why?

int main(/*int argc, _TCHAR* argv[]*/)
{
_TCHAR*?
because
under the covers the code has to first dereference the pointer that
implements the reference, then dereference the resulting pointer to get
at the actual data;

COMMENTS OF HW:

We know these are your comments.
I donot think an optimizing compliler would take that
roundabout path for implementing an int*&. Copying the contents of the
int*[ie the starting address of i or j] may be the approach taken.
It might. A common optimisation for small objects is to pass them by
value rather than by reference. In order to pass by reference, the
compiler has to calculate the address of the object to form the reference.
COMMENTS OF HW: This has always been a matter of opinion and taste,
but I think it is better to take the approach that maps to the
physical problem our code is solving. In this particular case passing
the pointers themselves by reference is closer to what our code is
trying to solve: write a funtion that swaps values pointed by two
pointers to int.
Why? The pointers are not being modified.
 
H

HumbleWorker

Hi,

No, it's silly. If you were given to integers to pass to a function,
would you pass reference to them?

COMMENTS OF HW:

We would pass them by reference if we are to act on them to modify
them back home. In this case we are modifying the contents of the
pointer and we are passing that particular pointer by reference.
int main(/*int argc, _TCHAR* argv[]*/)
{

_TCHAR*?

COMMENTS OF HW: I use MSVC compiler and I already commented off the
irrelevant portions of main. TCHAR is a Microsoft child, let us not
bother about it here, but I have seen them commented off in many
posts, so I did them.

We know these are your comments.

COMMENTS OF HW: I use this decoration for clarity.
Why? The pointers are not being modified.

I will give you a synonym:

Pointer = Class Object;
Pointer contents[dereferenced ones] = Class Object public member.

We pass a reference to Class Object if we intend to modify its
datamember back home, on the same analogy I am talking about the
pointer as a reference.

COMMENTS OF HW: I know that this was just a textbook exercise and we
all have been through them, but it is always interesting to re-read
the questions between the lines and try look at them philosophically.
But I do have a point.

Thanks,

HW
 
I

Ian Collins

HumbleWorker said:
We would pass them by reference if we are to act on them to modify
them back home. In this case we are modifying the contents of the
pointer and we are passing that particular pointer by reference.
That's where you misunderstand, in this example, the data pointed to by
the pointers is modified, not the pointers them selves. A pointer
stores an address, it is the contents of the address that changes, not
the address.

If the function were to change the address pointed to by the pointer, it
would have to be passed by reference.
COMMENTS OF HW: I use this decoration for clarity.
You don't have to, news readers no how to quote. Your decoration only
adds noise.
 
H

HumbleWorker

That's where you misunderstand, in this example, the data pointed to by
the pointers is modified, not the pointers them selves. A pointer
stores an address, it is the contents of the address that changes, not
the address.

If the function were to change the address pointed to by the pointer, it
would have to be passed by reference.

COMMENTS OF HW: I already wrote it clearly, that the contents are
derefenced ones.

FROM MY PREVIOUS POST:
I will give you a synonym:
Pointer = Class Object;
Pointer contents[DEREFERENCED ONES] = Class Object public member.

COMMENTS OF HW: Anyhow let us move on.

HW
 
W

wei

Do you want a more interesting algorithm to implement the task to swap
two values?
Here it is, but I think it is just a trick

void swap(int *ip, int *jp)
{
*ip = *ip ^ *jp;
*jp = *ip ^ *jp;
*ip = *ip ^ *jp;
}

int main()
{
int i = 3, j = 4;
swap(&i, &j);
cout<<i<<","<<j<<endl;
return 0;
}
 
J

James Kanze

Do you want a more interesting algorithm to implement the task to swap
two values?
Here it is, but I think it is just a trick
void swap(int *ip, int *jp)
{
*ip = *ip ^ *jp;
*jp = *ip ^ *jp;
*ip = *ip ^ *jp;
}

A classical example of code which doesn't work.
int main()
{
int i = 3, j = 4;
swap(&i, &j);

Try:
swap( &i, &i ) ;
(That should work too.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

C++ Primer ex 7.5 18
C++ Primer ex 4.16 2
C++ Primer ex 3.14 8
C++ Primer ex 9.27 4
C++ Primer ex 3.24 (bitset class) 5
C++ Primer ex 7.12 2
C++ Primer ex 5.18 5
C++ Primer ex 4.30 10

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top