Cocoa: confused #define in code?

I was looking at some code that I downloaded from the internet ( Got it here )

I am confused with this line of code ... What exactly does it do?

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

      

Here is an array of "random words":

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

      

+1


a source to share


2 answers


sizeof(randomWords)

specifies the number of bytes occupied by the array. Each element of the array is a pointer NSString

. sizeof(NSString*)

sets the size of each pointer. So dividing the total size by the size of each item gives the number of items.

N_RANDOM_WORDS

- macro. Wherever it is used, the expression sizeof(randomWords)/sizeof(NSString*)

will be inserted in place by the preprocessor. Usually these are constants defined in C or Object C.



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

+5


a source


One NSString*

takes bytes sizeof(NSString*)

. The size randomWords

is equal N * sizeof(NSString)

. So for a solution N

you get N = sizeof(randomWords)/sizeof(NSString *)

.



+1


a source







All Articles