For what reasons?

B

Bob Jenkins

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
 
?

=?ISO-8859-1?Q?Daniel_Sch=FCle?=

Bob said:
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
 

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

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top