Using variables created in function into the main

Hello. My question is rather stupid but anyway: What are the ways so the main has access to the variable created in a function and vice-versa? Here the problem is of course that the variable "s" has not been declared.

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
#include <iostream>
using namespace std;

void add();

int main(){
    
    add();
    cout<<s<<endl;
    
    
}


void add(){
    float a;
    float b;
    float s;  //sum
    
    cin>>a;
    cin>>b;
    
    s = a + b ;
  
}


Sorry for the probably stupid question but I don't have a professor so I will annoy you. Thank you in advance.
Your solution would be simply to make the function return it.

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;

float add();

int main(){
    
   float s =  add();
    cout<<s<<endl;
    
    
}


float add(){ 
    float a;
    float b;
    float s;  //sum
    
    cin>>a;
    cin>>b;
    
    s = a + b ;
    return s;
  
}


Edit: Corrected my mistake, thank you @AbstractionAnon.
Last edited on
@TarikNeaj - Line 7: You need to declare s within main.

 
  float s;


Thank you guys very much. The tutorials that I was watching never mentioned what the return does. So what it does if I understood correctly is saying that the value "s" can be used and into the main. Right?
OK. Just read the article that you have in this site and now everything is clear. Thank you
Another relevant question. If I want to return more than 1 values can I just write many times "return x;"?
Another relevant question. If I want to return more than 1 values can I just write many times "return x;"?


No.

If you want to return many values, pass them in by reference, or pass in pointers to them, or return some kind of composite variable containing many sub-variables (like a struct), or return a container of variables.
Topic archived. No new replies allowed.