C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Passing Pointers
Goto page Previous  1, 2, 3, ... 17, 18, 19  Next
 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
John Harrison
Guest





PostPosted: Fri Mar 05, 2004 8:29 am    Post subject: Re: Passing Pointers Reply with quote




"Paavo P" <etunimi.keskinimi.takanimi (AT) sserveri (DOT) fi> wrote

Quote:
Here's my prob:

function:

char* cat(char* a,char* b){

int size=(strlen(a)+strlen(b)+1);

char* ab=new char[size]; //reserve space with new-operator is in
preconditions

Good so far.

Quote:
char* x=NULL;

while(*x++=*a++);

Well you are obviously trying to copy the memory pointed to by a to the
memory pointed to by ab using the pointer x. The problem is that you have
not made x point to the place you want to start copying from (i.e. a). Also
the 'cute' but terse syntax *x++ = *a++ is just too confusing. Try this

char* x = a;
while (*a != '') // while not at the end of string
{
*x = *a; // copy one char from a to x
++x; // move x on
++a; // move a on
}

john



Back to top
Bjarne Stroustrup
Guest





PostPosted: Fri Mar 05, 2004 5:48 pm    Post subject: Re: Passing Pointers Reply with quote



"Paavo P" <etunimi.keskinimi.takanimi (AT) sserveri (DOT) fi>
Quote:

Why is the instructor not using the 3rd edition. That one is up-to-date
with the current standard.

3rd was not available in Finnish.

It has been for a while now: Finnish translation 2000; Teknolit; ISBN 951-846-026-4.

-- Bjarne Stroustrup; http://www.research.att.com/~bs

Back to top
B. v Ingen Schenau
Guest





PostPosted: Fri Mar 05, 2004 5:59 pm    Post subject: Re: Passing Pointers Reply with quote



John Harrison wrote:

Quote:

"Paavo P" <etunimi.keskinimi.takanimi (AT) sserveri (DOT) fi> wrote in message
news:iBC1c.10682$k4.227513 (AT) news1 (DOT) nokia.com...
Here's my prob:

function:

char* cat(char* a,char* b){

int size=(strlen(a)+strlen(b)+1);

char* ab=new char[size]; //reserve space with new-operator is in
preconditions

Good so far.

char* x=NULL;

while(*x++=*a++);

Well you are obviously trying to copy the memory pointed to by a to the
memory pointed to by ab using the pointer x. The problem is that you have
not made x point to the place you want to start copying from (i.e. a).

As x represents the target for the copy operation, it should be initialised
to ab.

Quote:
Also the 'cute' but terse syntax *x++ = *a++ is just too confusing. Try
this

char* x = a;

Change this to
char* x = ab;

Quote:
while (*a != '') // while not at the end of string
{
*x = *a; // copy one char from a to x
++x; // move x on
++a; // move a on
}

john

Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://ma.rtij.nl/acllc-c++.FAQ.html
c.l.c FAQ: http://www.eskimo.com/~scs/C-faq/top.html
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/

Back to top
Baxter
Guest





PostPosted: Sat Jan 28, 2006 2:38 am    Post subject: Re: Comment on style Reply with quote

<pocmatos (AT) gmail (DOT) com> wrote in message
news:1138352969.484397.312110 (AT) g47g2000cwa (DOT) googlegroups.com...
Quote:
Hi all,

While I was programming 5 minutes ago a recurring issue came up and
this time I'd like to hear some opinions on style. Although they are
usually personal I do think that in this case as also to do with making
the code easier to read.

Imagine a function returning void (for example) and it's body is a big
if with lots of special cases:

void foo(const MyClass &c) {
if(c.bar()) {
x();
} else if(c.foobar()) {
y();
} else if(c.mybar()) {
z();
}
}

The question is if you prefer to see like I've wrote it or with a
return; after a call to x(), and another one after a call to y(), etc
etc... ?



My preference is:

void foo(const MyClass &c)
{
if (c.bar()) {
x();
}
else if (c.foobar()) {
y();
}
else if (c.mybar()) {
z ();
}
}

This is a Modified K&R, and (IIRC) used by the BCD.

Note the following:
- only one brace on a line. Brace, opening or closing, is followed by c/r
- body of conditionals are indented (for easy reading)
- opening brace for _function_ is on line by itself (largely for historical
reasons)
- leading brace on same line as conditional,
-- reduces visual redundancy of implied "begin",
-- opening brace is _always_ related to conditional. If on same line,
you cannot accidentally insert code.
-- reduces vertical whitespace improving readability
-- allows easy insertion of new code, or deletion of old code block.
-- gives greater correspondence with English:
if (conditional)
DoThis; // body of conditional
end conditional
-- presents no known problems with any debugger.

YMMV

--
---------------------------------------------------------------------
DataGet® & PocketLog® www.dataget.com
Data Collectors www.baxcode.com
--------------------------------------------------------------------
Back to top
Aaron Graham
Guest





PostPosted: Sat Jan 28, 2006 2:38 am    Post subject: Re: Comment on style Reply with quote

A lot of things are a matter of preference but many things are not.
Usually when I'm faced with the task of choosing a consistent style
guideline or tool or environmental preference, I first consider the
following:

1) If I was equally "fluent" in both styles, would one of them be
superior in any respect?
2) Is it too difficult or are there other barriers to becoming "fluent"
in either style?

Sometimes, (1) turns out to be "no", or more often "nothing comes to
mind", in which case it certainly is a matter of preference. Sometimes
(2) turns out to be "yes", in the sense that one style is more
difficult to become accustomed to, or because one requires a
substantial amount of mental faculty that the other doesn't.

Take, for instance, the hypothetical argument of Windows Notepad vs.
Emacs as a development environment The answer to question (1) is "yes"
because emacs is more powerful and will help you be a more productive
developer than Windows Notepad will, given that you know them equally
well. The answer to (2) is "yes" because emacs takes more effort to
get to know and learn to use well. This is an extreme example, but it
shows that Windows Notepad vs. Emacs is not so much a matter of
preference as it is a matter of effort or learning curve. Nobody who
knows emacs well will voluntarily use Windows Notepad for code
development. You'll never hear someone say "I know how to use emacs,
but I like Windows Notepad better." The argument of C vs. C++ or GUI
vs. CLI is somewhat similar.

Now, apply these questions to brace styles: The answer to (1) is
"yes," being able to fit more code on a single page is certainly
better, readability notwithstanding. Someone who is _equally_fluent_
in both styles will find that he can be more productive if he's not
hampered as much by the physical act of scrolling. Note that this
point is NOT subjective. People who could scroll around faster than
they could move their eyes would probably make their windows only a few
lines tall, but I can't be sure because I don't know anyone like that.
So it comes down to (2) which is the part of the question that
addresses readability, and is the only part that is subjective. Since
it took me a little longer to learn to read vertically compressed code
well, I can admit that it takes more experience and some adjustment for
your mind to get over the perception of the code being "cluttered", but
I don't think it was _too_ difficult.

So I would have answered "no" to (2) but maybe some people just can't
get their minds over the "cluttered" aspect. I'm pretty sure that
people who consistently write code in one-line-per-brace style would
have difficulty ever getting over it. (As an analogy, it's much harder
to learn a language well unless you speak or write it.) So maybe
you're right in one aspect -- it takes an undesirable amount of effort
for some people to learn to read vertically compressed code as well.
Some people work for draconian companies that enforce a certain style,
so they never really get much of chance to learn to write or read
differently-styled code. I've worked for and have dealt with such
companies before. (I even worked with a company that required
developers to mix spaces and tabs in their indentation, and to use a
brace style that I've _never_ seen anyone else use. I personally think
it was more of an obfuscation technique than anything else.)

As an extreme, regarding code with NO non-essential whitespace (except
for word-wrap at column 80 or so), the answer to (1) is still "yes",
but the answer to (2) is also a resounding "yes", since the amount of
effort required to read it is excessive. But once again, it's not as
much a matter of personal preference as it is effort or mental faculty.

Quote:
Not if the time it takes to comprehend vertically compressed code is
greater than the time it takes to scroll the page back and forth. I am
also familiar with both styles. It so happens that the style I find
easier to read is the one you find harder to read. I still think that
says nothing whatsoever about our relative skills as programmers.

Sorry, I shouldn't have said anything about programming skill. I was
just stating a strong observed correlation, but there are certainly
outliers, and I don't doubt your programming abilities.

This really is a silly topic to have so much debate about. I'll be off
now.

Aaron
Back to top
Jim Langston
Guest





PostPosted: Sat Jan 28, 2006 10:02 am    Post subject: Re: Comment on style Reply with quote

<pocmatos (AT) gmail (DOT) com> wrote in message
news:1138352969.484397.312110 (AT) g47g2000cwa (DOT) googlegroups.com...
Quote:
Hi all,

While I was programming 5 minutes ago a recurring issue came up and
this time I'd like to hear some opinions on style. Although they are
usually personal I do think that in this case as also to do with making
the code easier to read.

Imagine a function returning void (for example) and it's body is a big
if with lots of special cases:

void foo(const MyClass &c) {
if(c.bar()) {
x();
} else if(c.foobar()) {
y();
} else if(c.mybar()) {
z();
}
}

The question is if you prefer to see like I've wrote it or with a
return; after a call to x(), and another one after a call to y(), etc
etc... ?

Cheers,

Paulo Matos

From structured programming, a function is supposed to only have one exit
point. Meaning the way you have it is correct. The justification for this
is that it's much easier to understand the flow of a function, top/down.

Say your function was in fact like this:

void foo(const MyClass &c)
{
if (c.bar())
{
x();
return;
}
else if (c.foobar())
{
y();
return;
}
else if ( c.mybar() )
{
z();
return;
}

zz();

}

Which I've actually seen in code. If someone was searching code to see
where zz() was called and the if statements were actually many lines, one
could presume wrongly that zz() is always called in the function foo. In
fact it's only called if the other conditions are not met.

Then comes the fun when, say, else if ( c.foobar() ) doesn't have a return
in it's block. So both y() and zz() are called in that instance, another
case I've seen. Then it becomes even more confusing when zz() is called and
isn't.

Of course the "proper" way would be to get rid of the returns, and wrap the
call to zz() in an else statement, then it once again becomes clear. And
have the c.foobar() also call zz() if it needs to.

Top down coding requires there only be one exit point for a function, but as
I think we all know, rules are made to be broken. There are some situations
it just makes the function much clearer as to what it's doing to have a
return statement other at the bottom of the function, but this should be the
exception rather than the rule in top down coding.
Back to top
Kai-Uwe Bux
Guest





PostPosted: Sat Jan 28, 2006 3:05 pm    Post subject: Re: templated pointer function for simple array Reply with quote

shaun roe wrote:

Quote:

....

This still allows me to add extra 'magic numbers' in my const array at
the top of the file without changing any subsequent code. I'm not
entirely happy that I have to pass both 'a' and 'sizeof(a)' since it
feels like the 'sizeof' should be redundant, but I understand why it
isn't.

What about my solution?

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}

Maybe I didnt properly understand, but isnt Size the number of elements?
If I change the const array at the top of the file, I would have to
change all my calls to reflect the new number of members.


In the syntax

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}

the identifier "Size" is a template parameter. You will not need to change
anything. Try the following on your compiler, which uses the same trick:

template < typename T, unsigned long N >
unsigned long length_of ( T const (& arg) [N] ) {
return( N );
}

#include <iostream>

const double a[] = { 2.3, 4.5, 6.6, 8.0, 10.0 };

int main ( void ) {
std::cout << length_of( a ) << '\n';
}


This should print 5. Once you change it to

template < typename T, unsigned long N >
unsigned long length_of ( T const (& arg) [N] ) {
return( N );
}

#include <iostream>

const double a[] = { 2.3, 4.5, 6.6, 8.0 };

int main ( void ) {
std::cout << length_of( a ) << '\n';
}

it will print 4. As you can see, no change to the template is needed. The
compiler automatically deduces the correct value for Size (or N in my
version) upon initialization of the template at the point where it is
called.


Best

Kai-Uwe Bux
Back to top
shaun roe
Guest





PostPosted: Sat Jan 28, 2006 3:05 pm    Post subject: Re: templated pointer function for simple array Reply with quote

Quote:
....

This still allows me to add extra 'magic numbers' in my const array at
the top of the file without changing any subsequent code. I'm not
entirely happy that I have to pass both 'a' and 'sizeof(a)' since it
feels like the 'sizeof' should be redundant, but I understand why it
isn't.

What about my solution?

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}

Maybe I didnt properly understand, but isnt Size the number of elements?
If I change the const array at the top of the file, I would have to
change all my calls to reflect the new number of members.
Back to top
Rolf Magnus
Guest





PostPosted: Sat Jan 28, 2006 3:05 pm    Post subject: Re: templated pointer function for simple array Reply with quote

shaun wrote:

Quote:
OK, thanks all...after some experimenting, I came up with:

#include <iostream
using namespace std;
const double a[]={
2.3,4.5,6.6,8.0,10.0
};

template<class T> T * endof( T parray[], long unsigned int s){
return (parray+s/sizeof(parray[0]));
};

int main (int argc, char * const argv[]) {
const double * pEnd=endof(a,sizeof(a));
cout<<"Returned pointer: "<<pEnd<<endl<<endl;
cout<<"Outside the function: "<<endl;
cout<<"Array size: "<<sizeof(a);
cout<<" Element size: "<<sizeof(a[0])<<endl;
cout<<"Pointer to array start: "<<a<<endl;
int numElements=sizeof(a)/sizeof(a[0]);
const double * pEnd2= a+numElements;
cout <<"Pointer to one-past-end: "<<pEnd2<<endl<<endl;
cout<<"Pointer to a[5]"<<&(a[5])<<endl;
return 0;
}


....

This still allows me to add extra 'magic numbers' in my const array at
the top of the file without changing any subsequent code. I'm not
entirely happy that I have to pass both 'a' and 'sizeof(a)' since it
feels like the 'sizeof' should be redundant, but I understand why it
isn't.

What about my solution?

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}
Back to top
MikeB
Guest





PostPosted: Sat Jan 28, 2006 4:00 pm    Post subject: Re: A dying era Reply with quote

"P.J. Plauger" <pjp (AT) dinkumware (DOT) com> wrote in message
news:ue2dnQgZUcJXWCLeRVn-uw (AT) giganews (DOT) com...
Quote:
What killed CUJ is what's been killing newspapers slowly for...

Are you saying that CMP intend to stop publishing a print version of CUJ?
I've searched the web and both the CMP and CUJ sites but can't see anything
about this. I accidentally let my subscription lapse so the January issue
was the last I got. I saw no mention of it there. If they are dropping it,
do you know which will be the last issue to ship?

Rgds,
MikeB
Back to top
shaun roe
Guest





PostPosted: Sat Jan 28, 2006 4:00 pm    Post subject: Re: templated pointer function for simple array Reply with quote

Quote:

In the syntax

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}

the identifier "Size" is a template parameter. You will not need to change
anything. Try the following on your compiler, which uses the same trick:


EXCELLENT! exactly what I wanted, many thanks!

shaun
Back to top
Rolf Magnus
Guest





PostPosted: Sat Jan 28, 2006 4:00 pm    Post subject: Re: templated pointer function for simple array Reply with quote

shaun roe wrote:

Quote:

....

This still allows me to add extra 'magic numbers' in my const array at
the top of the file without changing any subsequent code. I'm not
entirely happy that I have to pass both 'a' and 'sizeof(a)' since it
feels like the 'sizeof' should be redundant, but I understand why it
isn't.

What about my solution?

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}

Maybe I didnt properly understand, but isnt Size the number of elements?

Yes.

Quote:
If I change the const array at the top of the file, I would have to
change all my calls to reflect the new number of members.

No, you won't. You just call it like in your original posting. The number of
elements is automatically deduced.
Back to top
Daniel T.
Guest





PostPosted: Sat Jan 28, 2006 5:00 pm    Post subject: Re: Subscript operator overloading with vectors Reply with quote

In article <BKCCf.1399$tO6.1018 (AT) fe05 (DOT) lga>,
"Jim Langston" <tazmaster (AT) rocketmail (DOT) com> wrote:

Quote:
You got your answers in other posts. Just a comment on your code

olson_ord (AT) yahoo (DOT) it> wrote in message
news:1138364089.654880.230480 (AT) g14g2000cwa (DOT) googlegroups.com...
Hi,

I am not exactly new to C++, but I have never done operator
overloading before.
I have some old code that tries to implement a Shift Register - but I
cannot seem to get it to work. Here's a simpler version of it.

-------------------- main.cpp---------------------------

# include <iostream
# include <vector
# include <cassert

class ShiftRegister {
public:
ShiftRegister(unsigned size) : _reg(size) {

}

_reg is a no no. You shouldn't use an underscore as the first char of a
variable/function/whatever.

There is absolutely no problem with a member-variable having a
underscore as its first character as long as the next character is not
an upper-case letter.

The restrictions are as follows:

any global-scope name beginning with _.
any name beginning with _ followed by an upper-case letter.
any name containing __.
Back to top
Mark Stijnman
Guest





PostPosted: Sat Jan 28, 2006 9:00 pm    Post subject: Re: Forward iterators and past-the-end iterator Reply with quote

Thanks for your suggestion, it definitely has its merits - the most
important that I see is that the details of having the thread wait for
the "new items available" signal is hidden inside the iterator. It also
defines a mechanism to alert the reading threads of the fact that there
will be no more new data. The one disadvantage I see is that it might
make the thread irresponsive to other events. In my case, one or more
of the threads will more than likely be doing network communication as
well. I will have to think whether this is a real problem though.

best regards Mark
Back to top
Mark Stijnman
Guest





PostPosted: Sat Jan 28, 2006 9:00 pm    Post subject: Re: Forward iterators and past-the-end iterator Reply with quote

Victor Bazarov wrote:
Quote:
I think the dilemma is solved not by providing the documentation, but
rather by examining the possibility of somebody (even yourself) using
the code with any other container rather than your own with its special
iterator.

What happens here is that after the signal arrives, the first thing you
are going to be doing is dereferencing the iterator, then incrementing it
in the last loop. Both operations are definitely invalid for iterators
from 'std::list', for example.

Generally speaking, once the iterator got the value "one after the last"
it should be impossible for any code outside the thread that owns that
iterator object to change its meaning (by somehow changing its value).

Store the iterator to the "last" element and increment it after you get
the signal:

MyContainer ReadThis; // a container
MyContainer::const_iterator ReadIter = ReadThis.begin(), RT;

for (RT = ReadIter; RT != ReadThis.end(); ReadIter = RT++)
cout << *RT << endl;

// at the end of the loop ReadIter is the iterator to the last read.

// Thread waits for ReadThis to have one more more items added.
WaitForItemsAddedSignal(...);

++ReadIter; // now it points to the next to read

for (RT = ReadIter; RT != ReadThis.end(); ReadIter = RT++)
cout << *RT << endl;

V

Thanks, that was the insight I was looking for. It does indeed seem
more logical that a past-the-end iterator will remain a
non-dereferenceable iterator, and not magically turn itself into a
dereferenceable iterator when you are not looking. Also, like you
pointed out, your approach makes it work with all other containers that
support forward iterators.

best regards Mark
Back to top
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Goto page Previous  1, 2, 3, ... 17, 18, 19  Next
Page 2 of 19

 
 


Powered by phpBB © 2001, 2006 phpBB Group