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>
usingnamespace 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>
usingnamespace 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>
usingnamespace 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 { }.