Concering return and declaring varibles

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().


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int  function1();
void function2(int);

int main()
{
    function1();
    function2(x);
        return 0;
}

int function1(){

    int x;
    x=5;

    return(x);
}

void function2(int){

    cout<<x;
}
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().

Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using namespace 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; 
}


Now this code would also be valid:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace 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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

void function1();
void function2();
int x; //declared globally

int main()
{
    function1();
    function2();
    return 0;
}

void function1(){
    x=5;
}

void function2(){
    cout<<x;
}


Global variables are common in C, but are usually frowned upon in C++ as this can make things quite confusing when things get complicated.
Last edited on
Topic archived. No new replies allowed.