Tuesday, December 02, 2008

The things you learn...

Every programmer learns how to pass things by reference. Arguably, most of us learn how to pass pointers back and forth. The trick is, remembering how to do it when you haven't tried in a long time! For instance, I tried to pass "by reference" in Objective-C the other day and got a nice error. Turns out, you have to do it c-style with pointers and addresses... or you can change the compiler to objective-c++ and continue to do by reference. In either case, the program is below with the output after that.

void myfunc2( int &a, int &b ) //c++ by reference;
{
a = a + 2;
b = b + 6;
NSLog(@"a: %i, b: %i", a, b );
}

void myfunct( int *a, int *b ) //c passing pointers
{
*a = *a + 1;
*b = *a + 2;
NSLog(@"a: %i, b: %i", *a, *b );
}

int main (int argc, const char * argv[])
{

int one, two;
one = two = 3;

NSLog(@"one: %i, two: %i", one, two );

myfunct(&one, &two); //c-style way of doing things

NSLog(@"one: %i, two: %i", one, two );

myfunc2( one, two ); //c++ style way of doing things

NSLog(@"one: %i, two: %i", one, two );

return 0;
}

OUTPUT:
[Session started at 2008-12-02 16:06:12 -0600.]
2008-12-02 16:06:12.513 test[4872:10b] one: 3, two: 3
2008-12-02 16:06:12.517 test[4872:10b] a: 4, b: 6
2008-12-02 16:06:12.518 test[4872:10b] one: 4, two: 6
2008-12-02 16:06:12.519 test[4872:10b] a: 6, b: 12
2008-12-02 16:06:12.520 test[4872:10b] one: 6, two: 12

The Debugger has exited with status 0.

No comments: