Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C "#if" syntax

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 ?

like image 763
johnbakers Avatar asked Oct 07 '11 02:10

johnbakers


People also ask

Is Objective-C same as C++?

While they are both rooted in C, they are two completely different languages. A major difference is that Objective-C is focused on runtime-decisions for dispatching and heavily depends on its runtime library to handle inheritance and polymorphism, while in C++ the focus usually lies on static, compile time, decisions.

Is C# the same as Objective-C?

Objective-C and C# are very different languages both syntactically and from a runtime standpoint. Objective-C is a dynamic language and uses a message passing scheme, whereas C# is statically typed.

Do people still use Objective-C?

Objective-C is so pervasive in iOS that it's impossible to completely remove it. Apple continues to maintain libraries written in Objective-C, so we should expect Objective-C to be treated as a (mostly) first class language in iOS. At other companies, legacy code remains.

Is Apple getting rid of Objective-C?

When Objective-C migration is perfect and developers beg managers for permission, Apple will say, "You should really be using Swift", and discourage Objective-C. Years later, it may be deprecated, but it never will be removed. It powers iOS, and years after deprecation OS X still runs bits of Carbon.


2 Answers

#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.

like image 74
Stuart Avatar answered Oct 02 '22 22:10

Stuart


#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.

like image 23
Jacob Relkin Avatar answered Oct 02 '22 22:10

Jacob Relkin