-2

I have a program that uses 3 separate files, a header file for function declarations, a cpp file for the definitions, and a main driver file to call the functions. For my function definitions, I have variables being created inside these functions that I wish to use as parameters for another function being called in main. I'm confusing myself just trying to put it into words, below is an example.

Header File

void function01(char);
void function02(int, int, char);

Cpp File

void function01(char a){

    int var01 = 3;
    int var02 = 4;
    int var03 = 8;
    char a = 'a';
}

void function02(int num1, int num2, int num3){
    int sum = num1 + num2 + num3;    
}   

Main File

int main (void){

    function02(var01, var02, var03);


return 0;
}

I know that as it is written now an error would be called. But is there anyway I can access the variables used in this first function so that I can call those same variables in main and pass them into my second function?

  • 1
    You should open your C++ book to the chapter that explains how to use classes and how they work, and start reading it. Unfortunately, stackoverflow.com is not a replacement for a C++ book. – Sam Varshavchik Feb 26 '20 at 03:11
  • @SamVarshavchik I apologize for the confusion, had classes been involved in this question the question would not have been asked. This question is from a C++ assignment in which classes can not be used. This is why the question has been asked. I have a pretty decent understanding as to how classes work. I also am not allowed to use them in the scenario from which my question is based. I appreciate the snide comment though, thank you for your help –  Feb 26 '20 at 03:22

1 Answers1

1

How to access the variables of a function inside main?

It is not possible to access non-static local variables of a function in a scope where that function is being called. Those variables exist only during function's execution. The objects named by the variables are created when the function is called, and destroyed before the function returns.

function01 is currently completely useless because it neither has any effects observable to the outside of the function, nor does it return anything. After calling the function the state of the program would be exactly the same as if you hadn't called the function. The function also doesn't do anything with its argument.

What you can do instead is return values from a function. It is only possible to return a single value. But you can group multiple objects inside a class. You could rewrite function01 like this for example:

struct my_example_class {
    int var01;
    int var02;
    int var03;
    char a;
};

my_example_class
function01(){
    return {3, 4, 8, 'a'};
}

Then call the other function and use the returned member objects as arguments to the other function:

auto r = function01();
function02(r.var01, r.var02, r.var03);
eerorika
  • 232,697
  • 12
  • 197
  • 326