just explain functions in general |
A function is basically a subroutine. When you "call" a function, you program will jump to the code inside that function. When that function "returns" (or exits), the program will jump back to the code that called it.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void func()
{
cout << "inside func" << endl;
}
int main()
{
cout << "before func" << endl;
func(); // <- call the function
cout << "between func" << endl;
func(); // <- call it again
cout << "after func" << endl;
}
|
before func
inside func
between func
inside func
after func |
The program starts in your main() function. From there, each line is executed. When you call func(), the program leaves main, jumps to the func() function, and runs all the code inside that function. When it's done, the program goes right back to where it came from in main.
Could someone explain to me the scope of variables |
Scope is basically the lifetime / accessibility of a variable.
For example:
1 2 3 4 5 6 7 8 9 10 11 12
|
void func(); // prototype the function
int main()
{
int myvar = 5;
func();
}
void func()
{
cout << myvar; // <- ERROR, myvar undeclared
}
|
This code will generate an error.
Scope of a variable is [usually] determined by its bounding {braces}. So here... since we are declaring the variable 'myvar' inside our main function... it is only accessible inside that function. It is not 'visible' anywhere else in the program.
So func() cannot see main's 'myvar' variable because it is no longer in scope.
If you want a separate function to have access to a variable... the typical way to do that is to pass that variable as a parameter:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void func(int); // prototype
int main()
{
int myvar = 5;
func( myvar ); // <- pass myvar as a parameter to func
}
void func(int myparam)
{
cout << myparam; // <- print the parameter
}
|
Here, we are creating a new variable named 'myparam' inside our 'func' function. When main calls func, it has to fill in a value for myparam. In this example... we are using 'myvar' to fill in the value.
Conceptually, it's like doing this:
|
int funcs_myparam = mains_myvar;
|
So now that we've "passed" myvar to func, we have its contents inside of the myparam variable. We can then print that through cout like normal and it'll work just fine.