Cocoa:对代码中的#define 感到困惑?
我正在浏览从互联网上下载的一些代码(在这里)
我对这行代码感到困惑......它到底在做什么?
#define N_RANDOM_WORDS (sizeof(randomWords)/sizeof(NSString *))
这是“randomWords”数组:
static NSString *randomWords[] = {
@"Hello",
@"World",
@"Some",
@"Random",
@"Words",
@"Blarg",
@"Poop",
@"Something",
@"Zoom zoom",
@"Beeeep",
};
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",
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
sizeof(randomWords)
给出数组占用的字节数。 数组的每个元素都是一个 NSString 指针。sizeof(NSString*)
给出每个指针的大小。 因此,将总大小除以每个元素的大小即可得出元素的数量。N_RANDOM_WORDS
是一个正在定义的宏。 无论在何处使用,表达式sizeof(randomWords)/sizeof(NSString*)
都将由预处理器插入其位置。 这通常是在 C 或 Objective C 中定义常量的方式。有关 C(和 Objective C)中宏的更多信息,这是一个很好的教程。
sizeof(randomWords)
gives the number of bytes taken up by the array. Each element of the array is anNSString
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 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.
一个
NSString*
占用sizeof(NSString*)
字节。randomWords
的大小为N * sizeof(NSString)
。 因此,求解N
,您将得到N = sizeof(randomWords)/sizeof(NSString *)
。One
NSString*
takessizeof(NSString*)
bytes. The size ofrandomWords
isN * sizeof(NSString)
. So solving forN
, you getN = sizeof(randomWords)/sizeof(NSString *)
.