- C++ Fundamentals
- Antonio Mallia Francesco Zoffoli
- 661字
- 2021-06-11 13:35:59
Function Declaration and Definition
A function declaration has the role of telling the compiler the name, the parameters, and the return type of a function. After a function has been declared, it can be used in the rest of the program.
The definition of the function specifies what operations a function performs.
A declaration is composed of the type of the returned value, followed by the name of the function and by a list of parameters inside a pair of parentheses. These last two components form the signature of the function. The syntax of a function declaration is as follows:
// Declaration: function without body
return_type function_name( parameter list );
If a function returns nothing, then the type void can be used, and if a function is not expecting any parameters the list can be empty.
Let's look at an example of a function declaration:
void doNothingForNow();
Here, we declared a function named doNothingForNow(), which takes no arguments and returns nothing. After this declaration, we can call the doNothingForNow() function in our program.
To call a function that does not have any parameters, write the name of the function followed by a pair of parentheses.
When a function is called, the execution flow goes from the body of the function currently being executed to the body of the called function.
In the following example, the execution flow starts at the beginning of the body of main function and starts executing its operations in order. The first operation it encounters is the call to doNothingForNow(). At that point, the execution flow goes into the body of doNothingForNow().
When all the operations inside a function are executed, or the function instructs them to go back to the caller, the execution flow resumes from the operation after the function call.
In our example, the operation after the function call prints Done on the console:
#include <iostream>
void doNothingForNow();
int main() {
doNothingForNow ();
std::cout << "Done";
}
If we were to compile this program, the compilation would succeed, but linking would fail.
In this program, we instructed the compiler that a function called doNothingForNow() exists and then we invoked it. The compiler generates an output that calls doNothingForNow().
The linker then tries to create an executable from the compiler output, but since we did not define doNothingForNow(), it cannot find the function's definition, so it fails.
To successfully compile the program, we need to define doNothingForNow(). In the next section, we will explore how to define a function using the same example.
Defining a Function
To define a function, we need to write the same information that we used for the declaration: the return type, the name of the function, and the parameter list, followed by the function body. The function body delimits a new scope and is composed of a sequence of statements delimited by curly braces.
When the function is executed, the statements are executed in order:
// Definition: function with body
return_type function_name( parameter_list ) {
statement1;
statement2;
...
last statement;
}
Let's fix the program by adding the body for doNothingForNow():
void doNothingForNow() {
// Do nothing
}
Here, we defined doNothingForNow() with an empty body. This means that as soon as the function execution starts, the control flow returns to the function that called it.
Note
When we define a function, we need to make sure that the signature (the return value, the name, and the parameters) are the same as the declaration.
The definition counts as a declaration as well. We can skip the declaration if we define the function before calling it.
Let's revisit our program now since we have added the definition for our function:
#include <iostream>
void doNothingForNow() {
// do nothing
}
int main() {
doNothingForNow();
std::cout << "Done";
}
If we compile and run the program, it will succeed and show Done on the output console.
In a program, there can be multiple declarations of the same function, as long as the declarations are the same. On the other hand, only a single definition of the function can exist, as mandated by the One Definition Rule (ODR).
Note
Several definitions of the same function may exist if compiled in different files, but they need to be identical. If they are not, then the program might do unpredictable things.
The compiler is not going to warn you!
The solution is to have the declaration in a header file, and the definition in an implementation file.
A header file is included in many different implementation files, and the code in these files can call the function.
An implementation file is compiled only once, so we can guarantee that the definition is seen only once by the compiler.
Then, the linker puts all of the outputs of the compiler together, finds a definition of the function, and produces a valid executable.
Exercise 3: Calling a Function from main()
In our application, we want to log errors. To do so, we have to specify a function called log(), which prints Error! to the standard output when called.
Let's create a function that can be called from several files, and put it in a different header file that can be included:
- Create a file named log.h and declare a function called log() with no parameters and that returns nothing:
void log();
- Now, let's create a new file, log.cpp, where we define the log() function to print to the standard output:
#include <iostream>
// This is where std::cout and std::endl are defined
void log() {
std::cout << "Error!" << std::endl;
}
- Change the main.cpp file to include log.h and call log() in the main() function:
#include <log.h>
int main() {
log();
}
- Compile the two files and run the executable. You will see that the message Error! is printed when we execute it.
- JavaScript前端開發模塊化教程
- 計算思維與算法入門
- LaTeX Cookbook
- Android開發精要
- 深入淺出Java虛擬機:JVM原理與實戰
- React Native Cookbook
- GitLab Repository Management
- PLC編程及應用實戰
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(入門與提高篇)
- Mastering ROS for Robotics Programming
- OpenResty完全開發指南:構建百萬級別并發的Web應用
- Mastering PowerCLI
- HTML5程序設計基礎教程
- C語言程序設計
- Access 2016數據庫應用與開發:實戰從入門到精通(視頻教學版)