Objective C “#if” syntax

让人想犯罪 __ 提交于 2019-12-21 03:19:15

问题


I'm a little confused by the "pound if" or #if syntax I see when I look at some classes.

For example:

#if someConstant == someNumber
  do something
#elif
  etc

versus:

if (someConstant == someNumber) 
   do something
else if {
   do more stuff
}

what's the difference, and why use #if ?


回答1:


#if etc are preprocessor directives. This means that they are dealt with before compiling and not at runtime. This can be useful, for example, in defining debugging behaviour that only compiles when you build for debug and not release:

#if DEBUG
    #define ISRelease(x) [x release]
#else
    #define ISRelease(x) [x release], x = nil
#endif

(Code courtesy of Jeff LaMarche's blog.)

This way you don't need to go through your entire application's code just before you submit your app and remove a load of debugging code. This is just one small example of the use of these directives.




回答2:


#if is a preprocessor directive.

if is a language construct.

The difference is in the way that the final program is compiled into. When you use #if, the result of that directive is what the final program will contain on those lines. When you use the language construct, the expression that is passed to the construct will be evaluated at runtime, and not compile-time.




回答3:


Previous answers cover #if usages from debug to terminology and miss one more common usage: #if is used to comment big chunks of code. This is useful when programmers needs to get rid of something which already contains comments.

#if 0
  a lof of C code with /* style */ comments included
#endif

I do use this a lot. Advantage over any other #if and comment style - it really does not care about most of broken syntax within it.



来源:https://stackoverflow.com/questions/7682400/objective-c-if-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!