'main()' is a function like any other function. The rules Lactose! and aregee explained above apply to any function. FunctionA() can't use FunctionB() unless FunctionB() is declared before FunctionA() is defined (there are some exceptions to this though).
The same thing applies to variables and variable types (like structs, classes, and enums).
You can't do this:
int y = x; //'x' hasn't been created yet!
int x = 0; //This needs to be above 'y = x'.
And you can't do this:
MyStruct foo; //'MyStruct' hasn't been defined yet!
struct MyStruct
{ ... };
And you can't do this:
void MyFunctionA()
{
MyFunctionB(123); //'MyFunctionB' hasn't been declared yet!
}
void MyFunctionB(int)
{
...
}
Declaration means you declare to the compiler that something with that name exists.
Definition means you define the actual details of that named thing.
Declarations:
struct MyStruct;
int MyFunction(int x);
Definitions:
struct MyStruct
{
int abc;
};
int MyFunction(int x)
{
//...
return x;
}
Definitions also declare, so you don't need to do this:
//Not necessary here:
// int MyFunction(int x)
//This serves as both a definition and a declaration:
int MyFunction(int x)
{
//...
return x;
}
Since definitions are also declarations, standalone declarations without definitions are also called pre-declarations (because they come before the full definition).
To use a function, the code only needs to be able to 'see' the declaration.
To declare a variable (like 'MyStruct foo'), the code must be able to 'see' the full definition of the variable type.
To declare a reference or pointer to a variable type (like 'MyStruct &ref'), only the declaration of that variable type is needed.
For the code to 'see' definitions or declarations, the definition or declaration must be vertically higher up the .cpp file.
Usually, function declarations are put in .h files, that are #included at the top of .cpp files.
When you #include a .h file (or any file type), it is basically copy+pasted into the .cpp file, so the function declarations in the .h file are now 'in' the .cpp file and can be seen by code vertically lower down the page.