Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book

Declaring Functions Using Prototypes

In the previous example, we defined the function in the code before calling it, so Objective-C knew about the greeter() function before it was called. But the function definition can also come after the call to that function in your code, like this:

#include <stdio.h>

int main()
{
  greeter();

  return 0;
}

void greeter()
{
  printf("Hello there.");
}

In this case, you must tell Objective-C about the greeter() function with a function prototype:

#include <stdio.h>

void greeter(void);

int main()
{
  greeter();

  return 0;
}

void greeter()
{
  printf("Hello there.");
}

Listing 4.3. Starting functionprototype.m.

#include <stdio.h>

void greeter(void);
       .
       .
       .
void greeter()
{
  printf("Hello there.");
}

Listing 4.4. The functionprototype.m program.

#include <stdio.h>

void greeter(void);

int main()
{
  greeter();

  return 0;
}

void greeter()
{
  printf("Hello there.");
}

A function prototype is just like the line where you declare a function (the line just before the function body inside curly braces), except that you remove the names of any function arguments (leaving just their types) and end the prototype with a semicolon.

The function prototype is also called the function declaration (as opposed to the function definition, which includes the body of the function).

You can also put function prototypes in header files, whose names end with .h, and then include them with stdio.h as shown in the listings here. That include statement includes the stdio.h header file, which includes prototypes for functions such as printf().

To create a function prototype:

  1. Create a new program named functionprototype.m.
  2. In functionprototype.m, enter the code shown in Listing 4.3.

    This code creates the greeter() function after the main() function and adds a prototype before the main() function so Objective-C knows about the greeter() function.

  3. Add the main() function to call the greeter() function (Listing 4.4).
  4. Save functionprototype.m.
  5. Run the functionprototype.m program.

    You should see the following:

    Hello there.
  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus