Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Difference between declaring and defining a function/enumerations in the C programming language

Could someone please explain me the Difference between declaring and defining a function/enumerations in the C programming language. I mean when it comes to defining and declaring a function we do almost the same thing, so whats the difference? This link might be able to give you an understanding of what I am trying to say https://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#Top

1 Answer

defining a function is where you actually provide a definition (what the function actually does) between { } like so:

//this is a definition
int addTwo(int a, int b) {

      return a + b

}

declaring a function is simply telling the compiler about the function. You let it know it exist by providing the name, the return type, and the number of / type of arguments.

//this is a declaration/prototype
int addTwo (int a, int b);

In C, you must either define a function before you use it, or provide a prototype declaration before you call the function and define the function somewhere else in the file. if you dont your program might not behave as you expect

Below is an example of providing a prototype, calling the function, and then defining the function below that

#include <stdio.h>

/* function declaration goes here.*/
int addTwo( int a, int b );

int main()
{
   int a = 10;
   int b = 20;

   //call the function here
   int c = addTwo(a, b)

}

//this is a definition
int addTwo(int a, int b) {

      return a + b

}

here is an example of defining the function first, then calling it:

#include <stdio.h>

//this is a definition
int addTwo(int a, int b) {

      return a + b

}

int main()
{
   int a = 10;
   int b = 20;

   //call the function here
   int c = addTwo(a, b)

}

notice we dont need the prototype declaration of the function since we defined it before we used it

most people prefer to use prototypes because its easier to organize your code that way since you dont have to worry about defining them before you use them

Nice job!