By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,234 Members | 2,075 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,234 IT Pros & Developers. It's quick & easy.

For what reasons?

P: n/a
Its not neccessary to return a pointer in a method/function, right ?
But for what reasons/under what circumstances do we have to do that ?

Thanks
Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Bob Jenkins wrote:
Its not neccessary to return a pointer in a method/function, right ?
you mean .. return pointer from the function
no, not necessary
But for what reasons/under what circumstances do we have to do that ?


mostly to prevent copying or to be able to *work* with the same object

struct X {
double d;
int i;
char big[1024];
};

// expensive call to foo

X * addToI(X * x, int inc)
{
x->i += inc;
return x;
}

X * writeToBig(X * x, const char * what)
{
strncpy(x->big, what, 1024);
return x;
}

#include <iostream>
int main()
{
X x = {0.0, 0, ""};
writeToBig( addToI(&x, 1) , "hallo World");
std::cout << x.big << x.big << std::endl;
}

as you can see, you can nest the calls to functions
and you work with the same object
cout verifies the changes

or imagine something like this

char * foo(int number)
{
static char big[1024];
sprintf(big, "your number was = %i", number);
return big;
}
it wouldn't work without static and you would be forced to copy it
somewhere else ..

hope this helps
Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.