Re: how to pass arguments by reference
Re: how to pass arguments by reference
- Subject: Re: how to pass arguments by reference
- From: Mark Woollard <email@hidden>
- Date: Wed, 10 Dec 2008 16:11:56 +0000
You can't use passing by reference in C or Objective-C, you can with C+
+ or Objective-C 2.0, for example the following will compile:
test.mm
#import <Cocoa/Cocoa.h>
// C++ function
int func( int& a )
{
return a * 2;
}
// Objective-C class
@interface test : NSObject
{
}
// Method using reference
- (int)func:(int&)a;
@end
@implementation test
// Implementation of method
- (int)func:(int&)a
{
return a * 2;
}
@end
Mark
On Dec 10, 2008, at 3:54 PM, Dave DeLong wrote:
Spoke too soon... whoops.
Put an asterisk before the type, indicating that the type is going
to come in as a pointer to the data and not the actual data. Then
when you call the method, you use the ampersand to pass a pointer to
your data, like so:
(in some class definition somewhere. A C function would have
slightly different syntax, shown below):
- (void) foo:(*int)bar {
(*bar)++;
}
Then elsewhere,
int baz = 42;
NSLog(@"%d", baz);
[someReceiver foo:&baz];
NSLog(@"%d", baz);
You should see "42" printed, and then "43".
If you wanted to declare "foo" as a C function, you'd do it like so:
void foo (int *bar) {
//same stuff
}
Welcome to the wonderful world of pointers.
Dave
On Dec 10, 2008, at 8:45 AM, Dave DeLong wrote:
Put the & before the variable type:
- (UInt32) traverseTreeStraightReturnedDirection:
(&int)treeDirection...
HTH,
Dave
On Dec 10, 2008, at 8:43 AM, Nick Rogers wrote:
Hi,
I have the following in my .m file:
- (UInt32)traverseTreeStraightReturnedDirection:(int&)treeDirection
returnedTreeDepth:(int&)treeDepth
returnedKey:(HPlusCatalogKey&)catKey
lookForKey:(HPlusCatalogKey)lastKey
{
// code here
}
But the error when compiling is "parse error before & token".
Is passing by reference not allowed or is there any other syntax
that I should follow?
Thanks,
Nick
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden