In the code below; Why can't I pass the return of funtion1() to main().
I understand the error which states "x was not declared in this scope." but shouldn't main() be expecting an integer return from function1()and have a place for it?
The reason I ask is because I have read and been told it's best practice to declare your variables where they first appear. If I am understanding that correctly x first appears in function1() and shouldn't be declared out of context in main().
Your value x is only declared in int function1(). At the end of the function, the value of x is returned to the main and the varible itself is destroyed. Therefore you can't use x outside of int function1().
#include <iostream>
usingnamespace std;
int function1();
void function2(int);
int main()
{
int a;
a = function1(); //a gets the value returned by function1
function2(a); //Now lets pass the value of a into function2
return 0;
}
int function1(){
int x;
x=5;
return(x);
}
void function2(int y){ // Declare the name of the variable you are using.
// y got the value of a in the main.
cout<<y;
}
#include <iostream>
usingnamespace std;
int function1();
void function2(int);
int main()
{
int x = function1();
function2(x);
return 0;
}
int function1(){
int x;
x=5;
return(x);
}
void function2(int x){
cout<<x;
}
Here I am declaring x in all three functions (main, function1, function2). These are all separate instances of x and they do NOT get the same value automatically. Whenever we come across the end of a function the x is destroyed in that function and needs to be built again.
Now, there are also such things as "global variables". We can declare x, outside of the functions and this means that it is shared everywhere like so: