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",
};
sizeof(randomWords)gives the number of bytes taken up by the array. Each element of the array is anNSStringpointer.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_WORDSis a macro being defined. Wherever it is used, the expressionsizeof(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.