A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times.
C++ provides some pre-defined functions, such as main()
, which is used to execute code. But you can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function, followed by parentheses ():
void
myFunction() {
// code to be executed
}
myFunction()
is the name of the functionvoid
means that the function does not have a return value. You will learn more about return values later in the next chapterDeclared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are called.
To call a function, write the function's name followed by two parentheses ()
and a semicolon ;
In the following example, myFunction()
is used to print a text (the action), when it is called:
Inside main
, call myFunction()
:
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
Try it Yourself »
A function can be called multiple times:
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
// I just got executed!
// I just got executed!
// I just got executed!
Try it Yourself »
A C++ function consist of two parts:
void
myFunction() { //
declaration
// the body of the function (
definition)
}
Note: If a user-defined function, such as myFunction()
is declared after the main()
function, an error will occur:
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
// Error
Try it Yourself »
However, it is possible to separate the declaration and the definition of the function - for code optimization.
You will often see C++ programs that have function declaration above main()
, and function definition below main()
. This will make the code better organized and easier to read:
//
Function declaration
void myFunction();
// The main method
int main() {
myFunction(); //
call the function
return 0;
}
//
Function definition
void myFunction() {
cout << "I just got executed!";
}
Try it Yourself »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!