Two functions of variables into one function

I have two variables in two different functions, I would like to store them in a third function without using global variables. How to do it?

something like that

void function1() { 
  a = 1;
  b = 2;
}

void function2() {
  c = 3;
  d = 4;
}

void function3 () {
  cout << a;  
  cout << b;  
  cout << c;  
  cout << d;  
}

      

+3


source to share


4 answers


Your functions can have values return

so you can pass variables to other functions, for example

std::pair<int, int> function1() {
    int a = 1;
    int b = 2;
    return {a, b};
}

std::pair<int, int> function2() {
    int c = 3;
    int d = 4;
    return {c, d};
}

void function3 () {
    int a, b, c, d;
    std::tie(a, b) = function1();
    std::tie(c, d) = function2();
    std::cout << a;  
    std::cout << b;  
    std::cout << c;  
    std::cout << d;  
}

      



Working demo

+6


source


Make methods of class functions and attributes of class variables.



class A
{
public:
int a;
int b;
int c;
int d;

void function1() { 
  a = 1;
  b = 2;
}

void function2() {
  c = 3;
  d = 4;
}

void function3 () {
  cout << a;  
  cout << b;  
  cout << c;  
  cout << d;  
}
};

      

+4


source


Use pass-by-reference:

int main() {
    int a;
    int b;
    function1(a, b);

    int c;
    int d;
    function2(c, d);

    function3(a, b, c, d);

    return 0;
}

void function1(int& a, int& b) { 
  a = 1;
  b = 2;
}

void function2(int& c, int& d) {
  c = 3;
  d = 4;
}

void function3(int a, int b, int c, int d) {
  cout << a;  
  cout << b;  
  cout << c;  
  cout << d;  
}

      

+4


source


You can pass them by link

#include<iostream>
using namespace std;
void function1(int &a,int &b) {
    a = 1;
    b = 2;

}

void function2(int &c, int &d) {
    c = 3;
    d = 4;
}

void function3(int a1,int b1,int c1,int d1) {

    cout << a1;
    cout << b1;
    cout << c1;
    cout << d1;
}
int main(){
    int a = 0, b = 0, c = 0, d = 0;
    function1(a, b);
    function2(c, d);
    function3(a, b, c, d);



}

      

+2


source







All Articles