C++ from Basics to Mastery — Part 4
What is a function? Episode 2
The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.
In this article, let’s learn more about how to use basic functions.
#include <iostream>
void function1(){
std::cout << "function1!" << std::endl;
}
int main(){
function1();
function2();
return 0;
}
void function2(){
std::cout << "function2!" << std::endl;
}
The code does not compile. It may vary depending on the compiler, but main.cpp:9:5: error: ‘function2’ was not declared in this scope; You can see that an error appears.
In our eyesfunction2is declared, why doesn't the computer know? C language and most programming languages read code from the top. In other words, the code gives these commands to the computer.
The declaration of function1 is read and function1 is created in memory. The main function is executed and function1 and function2 are executed. The declaration of function2 is read and function2 is created in memory. (We will learn about Name Lookup failure later.)
Isn’t there something strange even for a human to read?
Trying to run it in main before function2 is declared causes a compilation error.
#include <iostream>
void function1(){
std::cout << "function1!" << std::endl;
}
void function2(){
std::cout << "function2!" << std::endl;
}
int main(){
function1();
function2();
return 0;
}
So, the code is expected not to cause an error.
Or, write a declaration above the main function that tells the compiler in advance only the type of the function, Implementation containing actual operations can be written under the main function.
#include <iostream>
void function1();
void function2();
int main(){
function1();
function2();
return 0;
}
void function1(){
std::cout << "function1!" << std::endl;
}
void function2(){
std::cout << "function2!" << std::endl;
}