views:

250

answers:

2

Hello,

I was going through some code that I downloaded off the internet (Got it here)

I am confused with this line of code... What exactly is it doing?

#define N_RANDOM_WORDS (sizeof(randomWords)/sizeof(NSString *))

Here is the array of "randomWords":

static NSString *randomWords[] = {
@"Hello",
@"World",
@"Some",
@"Random",
@"Words",
@"Blarg",
@"Poop",
@"Something",
@"Zoom zoom",
@"Beeeep",
};

Thanks

+5  A: 

sizeof(randomWords) gives the number of bytes taken up by the array. Each element of the array is an NSString pointer. sizeof(NSString*) gives the size of each pointer. So dividing the total size by the size of each element gives the number of elements.

N_RANDOM_WORDS is a macro being defined. Wherever it is used, the expression sizeof(randomWords)/sizeof(NSString*) will be inserted in its place by the preprocessor. This is usually how constants are defined in C or Objective C.

For more information on macros in C (and Objective C), here's a nice tutorial.

Jay Conrod
I get it. But just to be sure, if I was to do this: "#define NSLOG_IT (NSLOG @"logging")" And then in my code, i called NSLOG_IT, It would log out "logging"?
Daniel Kindler
I think you would want to write it as '#define NSLOG_IT NSLog(@"logging")'. You could then write a statement 'NSLOG_IT;' and it would print "logging" like you say.
Jay Conrod
Sorry I meant to write "NSLog". Thanks man
Daniel Kindler
One more question. Your saying by doing this, it gives the number of elements. Couldnt you have done something like [randomWords count]?
Daniel Kindler
Yes, [randomWords count] would be the right way to do it if you had an NSArray. However, what you have above is a regular old-fashioned C array. Since it is not an Objective C object, it cannot receive messages like count.
Jay Conrod
oh ok thanks man
Daniel Kindler
+1  A: 

One NSString* takes sizeof(NSString*) bytes. The size of randomWords is N * sizeof(NSString). So solving for N, you get N = sizeof(randomWords)/sizeof(NSString *).

n8gray