I guess the main problem is not being aware of something very important which is called scope! Scopes are usually opened by {
and closed by }
unless you create a global variable, it is only known inside the scope it has been introduced (declared).
you declared the function b
in global scope :
void b();
so after this every other function including main
is aware of it and can use it.
but you declared the variable a
inside the scope of main
:
int a = 5;
so only main knows it and can use it.
Please make note that unlike some other programming languages, names are not unique and not every part of the program recognize them in c and c++.
So the part:
void b() {
int a;
does not force the function b
to recognize the a
which was declared in main
function and it is a new a
.
so to correct this mistake simply give the value or reference of variable a
to function b
:
#include <iostream>
void b(int&);
int main() {
int a = 10;
b(a);
}
void b(int& a) {
std::cout << "Int a=" << a << std::endl;
}
please also note that the a
as argument of the function b
is not the same a
in the function main
.
The final tip is every argument for functions is known inside that function scope as it was declared inside the function scope!