473,405 Members | 2,160 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

C++ Primer ex 7.6

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] $

*/
--
http://arnuld.blogspot.com

Aug 10 '07 #1
12 1312
Hi!

arnuld schrieb:
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
Aug 10 '07 #2
Hi!

arnuld schrieb:
#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 <ostreamas well.

Frank
Aug 10 '07 #3
On 2007-08-10 14:19, Frank Birbacher wrote:
Hi!

arnuld schrieb:
>#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 <ostreamas well.
The draft of the next standard has been amended to better reflect
reality (i.e. you including <iostreamwill include <(i|o)stream>) since
there's no implementation of consequence out there that does not allow
the OP's code.

--
Erik Wikström
Aug 10 '07 #4
On Aug 10, 4:47 pm, arnuld <geek.arn...@gmail.comwrote:
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

Aug 10 '07 #5
On 2007-08-10 10:50:57 -0400, HumbleWorker <am****************@gmail.comsaid:
On Aug 10, 4:47 pm, arnuld <geek.arn...@gmail.comwrote:
>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)
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.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Aug 10 '07 #6
Hi!

Alf P. Steinbach schrieb:
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
Aug 10 '07 #7
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.

Aug 11 '07 #8
Hi,

On Aug 11, 8:56 am, Ian Collins <ian-n...@hotmail.comwrote:
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

Aug 11 '07 #9
HumbleWorker wrote:
On Aug 11, 8:56 am, Ian Collins <ian-n...@hotmail.comwrote:
>No, it's silly. If you were given to integers to pass to a function,
would you pass reference to them?

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.
>
>We know these are your comments.

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.

--
Ian Collins.
Aug 11 '07 #10
On Aug 11, 12:31 pm, Ian Collins <ian-n...@hotmail.comwrote:
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

Aug 11 '07 #11
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;
}

Aug 11 '07 #12
On Aug 11, 2:42 pm, wei <teng...@gmail.comwrote:
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.)

--
James Kanze (GABI Software) email:james.ka...@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Aug 11 '07 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Sandman | last post by:
Could anyone give me a tip about a good primer on object oriented php programming - why I should use it, the benefits, the drawbacks, the bugs, the glory? And, should I upgrade to php5 before...
1
by: Charles L | last post by:
Does anyone know where I can find errata for Stan Lippman's 'C++ Primer 2nd Edition'? Charles Leng
1
by: hugo | last post by:
what is L&L ,people or book?
5
by: hajime | last post by:
I purchased this book: C++ Primer, 4th Edition ISBN: 0201721481 in Australia. The right side of the last three lines on page 231 are not legible. A stain shows a piece of paper was on that part...
7
by: Lycan. Mao.. | last post by:
Hello, I am a newbie in C++ and I'm in trouble in choosing books, I hope some one who can give me some tips. I'm already know C and a little about Scheme, C#, Python, Lua and so on, and now I want...
2
by: W. Watson | last post by:
Is there a primer out there on these two items? I have the Python tutorial, but would like either a Tkinter tutorial/primer to supplement it, or a primer/tutorial that addresses both. Maybe there's...
20
by: arnuld | last post by:
I get an error, can't find what is the problem: /* C++ Primer - 4/e * * Chapter 8, exercise 8.3 * STATEMENT * write a function that takes and returns an istream&. the function should read...
2
by: xianwei | last post by:
First, typedef struct pair { Node *parent; Node *child; } Pair; static Pair SeekItem(cosnt Item *pI, const Tree *pTree) { Pair look;
1
by: Kveldulv | last post by:
Hi all, here is the code: http://pastebin.com/m6e74d36b I'm stuck at highfink constructor, last line before #endif. As parameters, I have reference to one parent class and int member of another...
0
by: cincerite | last post by:
Hello , guys , I'm reading C++ Primer 3rd edition recently.I tried to download the errata of it from Stan Lippman's Home Page:http:// staff.develop.com/slip/ ,but it says:We're Sorry, we could not...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.