When you declare a function with value parameters, such as
void func(int i)
you are declaring inputs.
#include <iostream>
void func(int i)
{
// the 'i' you see here is a local variable.
i = 10;
// we changed the local thing called 'i', when
// we exit in a moment that 'i' will go away.
}
int main()
{
int i = 1;
func(i);
// if we print 'i' here, it will be our version of i.
std::cout << "i = " << i << '\n';
return 0;
}
The i
parameter to func
is local to func
; this confuses new C++ programmers especially in the above scenario, it looks like you are passing i
itself into func rather than passing the value of main::i.
As you get further into C/C++ you'll discover 'reference' and 'pointer' types which allow you to actually forward variables to functions rather than their values.
When your function is actually doing is fetching a user input value and then passing that back to the caller, or returning it.
int attempt()
{
std::cout << "Take a guess!\n";
int guess;
std::cin >> guess;
return guess;
}
We tell the compiler that "attempt" takes no arguments and will return an int value. Then at the end of the function we use return
to do exactly that.
return
can only pass back one value - again, later you will learn about pointers and references, which will allow you to return something larger than a single value.
To receive this value to your main:
int main() {
int answer = (rand() % 10) + 1;
srand(time(0));
std::cout << "I am thinking of a number between 1 and 10. Try to guess it in 3 attempts!";
std::cout << endl;
int guess = attempt();
std::cout << "You guessed: " << guess << '\n';
cin.get();
return 0;
}
Or you can break the variable declaration and use into two lines:
int guess;
...
guess = attempt;
A key thing to take away from all this is that you can have different variables with the same name in different 'scopes':
int i = 1; // global, visible to all functions in this compilation unit.
int main()
{
srand(time());
int i = 2;
if ((rand() % 4) == 0) // 1 in four chance
{
// this is essentially a new scope.
int i = 10;
}
// here, i = 2.
}
void foo()
{
// here, i = 1 - we see the global since we didn't declare our own.
}
void foo2(int i)
{
// here, i is whatever value we were called with.
if (i == 1)
{
int i = 99;
}
// we're back to the i we were called with.
}