A Step Forward (or: Objective-C Doesn’t Need Forward Declarations Anymore)

by Joey deVilla on October 3, 2012

The Old Way: Forward Declarations

The Commodore 64 is from about the same era as Objective-C. The 64 hit the market in 1982; Objective-C (and C++ as well) first appeared in 1983.

Older languages like C (and recently, Objective-C), won’t just let you call a function or method whose definition is later on in the same file. Consider these two C functions, which appear in my Inpulse Magic 8-Ball tutorial:

The function set_time_mode refers to update_time_display, whose definition comes after set_time_mode‘s. As far as the C compiler is concered, set_time_mode doesn’t exist yet, and it will refuse to compile, giving you an error message that looks something like this:

You can’t simply switch the order of the two functions since update_time_display also calls set_time_mode.

Forward declarations solve this problem. By including the signature for update_time_display before the definition of set_time_mode, we give the compiler enough information so that it knows what to do with update_time_display when it’s compiling set_time_mode:

The code above compiles.

The New Way: No Forward Declarations

Newer languages like Python and Ruby don’t need forward declarations. You can have a method refer to another method that appears later in the file in Python:

And here’s the Ruby equivalent:

Objective-C joins the club in Xcode 4.3 and later (as of this writing, the current version of Xcode is 4.5); you no longer need to make forward declarations. The compiler will “look ahead” if the function or method it’s compiling makes calls to functions or methods that appear later on in the file.

This means that the following code compiles in Xcode (at least in Objective-C):

{ 2 comments… read them below or add one }

Leave a Comment

{ 1 trackback }

Previous post:

Next post: