Up until now, we have been declaring functions at the same time we have defined them. But it is possible to declare a function without defining it right away.
A function declaration is a statement that tells the compiler about a functionβs name, return type, and parameters. To write a function declaration with a definition, we write its prototype, but instead of providing the body, we just place a ; at the end:
When we declare a function, we are telling the compiler that the function exists and that it will be defined later. The declaration lets the compiler know βthere will be a function called doubleValue that takes in an int and returns an intβ. With that information, the compiler can look at a call to the function like int x = doubleValue(3); and decide if it makes sense or not. Later on, when the declaration is provided, the compiler can link that call to the code in the function.
A function definition is the actual implementation of the function. It is what we have seen up to now - the prototype plus the body of the function. (A definition always declares the function as well.)
int doubleValue(int num) {
int result = 2 * num;
return result;
}
This distinction allows us to write code where a function call comes before the definition of that function. This flexibility is useful when we have multiple functions that call each other, or when we want to separate the implementation of a function from its use. Say I want to put the main function in my program at the top of my code file. I can do so by first declaring my functions, then writing main, then defining my other functions.
Try running the program above. Then comment out the declaration of doubleValue on line 5. That should produce a compile error on line 11. When the compiler gets to that line, it sees a call to doubleValue, but does not yet know about that function.
Think of a declaration as you making a promise to the compiler βthis function will existβ. When you define the function, you are fulfilling that promise. Here is a brief summary of when definitions and declarations must occur:
A function declaration must occur before the function is used. Although you would not want to on purpose, it is OK to declare a function multiple times. (You are just making the same promise multiple times.)
A function definition must occur once in the program, but can appear at any point after the declaration. If you try to define a function multiple times, it will be a compiler error.
Put these blocks of code into a valid order where the definition of main comes before any other function definition. There are many possible correct orderings.
If we wanted to create a function called isPrime, which takes an int input as a parameter and returns either true or false, which of the following would be the correct function declaration?