C/ObjC - parameter size. Using a pointer vs value
at what point should I be passing a pointer to data in my functions/methods, rather than just passing the value?
Obviously there's the cases where I want the function to operate on the given data, but what if I'm just passing the value for info/copying purposes?
For example, foo as a basic type:
void setFoo(int foo);
...
int foo = 1;
setFoo(foo);开发者_如何学JAVA
Now foo as a simple structure:
typedef struct {
int x;
int y;
} Foo;
void setFoo(Foo foo);
...
Foo foo = {1, 2};
setFoo(foo); // Apple code does this kind of thing with CGSize, CGPoint...
But what if foo is a bigger struct...
typedef struct {
int x;
int y;
int z;
char str[256];
} Foo;
void setFoo(Foo *foo); // Now taking a pointer instead.
...
Foo foo = {1, 2, 3, etc ... };
setFoo(&foo);
Q. At what point here should I start using a pointer when providing data to a function?
Thanks
When on embedded systems, I think it's good practice to pass pointers (or references) for anything that's not a primitive type. This way your struct can grow and add members as needed without affecting the amount of data that is copied. Needless copying is a good way to slow down your system, so avoid it when you can. Getting into that habit will help in the long run I think.
If you use references and/or pointers to [const] objects as appropriate, "when" becomes "all the time"
精彩评论