using a variable in function and int main

I have a problem with using variables in the int main and a function like a void.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

void hi(){
  int a = 1;
}

int main(){
  int a;
  cout<<a;
  return 0;
}

How can I get int main to display the right number?
Hello?
Hello!
First off, you never call the function.

Second, if you want to print the value and not return it you need to print it in the function.

Assuming that you called hi(), as you have it, it would assign a value of 1 to a which is destroyed as soon as the function ends therefore doing nothing. So, either like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

void hi(){
  int a = 1;
  cout<< a;
}

int main(){
  hi();
  return 0;
}

or give it a return value:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int hi(){
  int a = 1;
  return a;
}

int main(){
  int a;
  a = hi();
  cout<<a;
  return 0;
}
int main is displaying the 'right' number. You declare a variable at line 10 and output it at line 11. Well, there is an error, the variable was not initialised, so the value displayed is garbage.

if you want to return a value from a function, declare the function to have a suitable return type, instead of void. And before exiting from the function, add a return statement to specify which value is to be returned.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

int hi(){
    int a = 1;
    return a;
}

int main(){
    int b = hi();
    cout << b;
    return 0;
}

Note that the variable a declared inside function hi() is a completely different variable to b declared in main(). As you discovered, you can re-use the variable name because the scope of the variable is limited by the braces { }.

See tutorial:
http://www.cplusplus.com/doc/tutorial/namespaces/
http://www.cplusplus.com/doc/tutorial/functions/
Last edited on
Thanks so much!
The function tutorial (linked by Chervil) has a section about arguments passed by reference. Hence:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

void hi( int & a ){
    a = 1;
}

int main(){
    int b = 0;
    hi( b );
    cout << b;
    return 0;
}
Topic archived. No new replies allowed.