Reputation: 2960
I must access variables declared inside other function.
Assume f1()
void f1()
{
double a;
int b;
//some operations
}
and f2()
void f2()
{
//some operations
//access a and b from f1()
}
Is it possilbe in c++? How can that be done?
Passing reference to function as shown here is not suitable answer for my case because this corrupts the order of calling functions. Declaring global variables also denied.
Upvotes: 1
Views: 26207
Reputation: 1
#include<iostream>
using namespace std;
class c1 {
string a;
string b;
public:
void f1();
void f2();
};
void c1::f1() {
cin >> a;
cin >> b;
f2();
}
void c1::f2() {
cout << "vals are: " << a << b;
}
Upvotes: 0
Reputation: 772
What you can do is something similar as what greatwolf suggested. You can use a class declaration inside your function. This serves the following purpose: You can define a function that is only available in the current scope, so not accessible outside of that scope and that function has access to variables within that scope as if they were global. The class is also only defined in your current scope.
void MyVeryComplicatedFunction
{
int A;
class localvars
{
public:
int *ARef; // this serves as the "Global" variables
std::vector<int> B; // this serves as the "Global" variables
localvars(int *inA) ARef(inA);
void RepetativeOperation(int C) {
(*ARef) += C;
B.push_back(C);
}
}localvars(A);
localvars.B.push_back(4);
A = 3;
localvars.RepetativeOperation(2);
localvars.RepetativeOperation(4);
localvars.RepetativeOperation(8);
printf("A = %d, B[3] = %d", A, localvars.B[3]);
}
Upvotes: 0
Reputation: 66459
It sounds like you want to call f2
from some other place than f1
, e.g.
void foo() { f1(); f2(); }
If that's the case: those variables don't even exist at the time f2
is called, so there's nothing to access.
(And you're mistaking scope for lifetime. Those are very different things.)
One thing you can do is pass the variables by reference to all the functions that need them.
void f1(double& a, int& b);
void f2(double& a, int& b);
void foo()
{
double x;
int y;
f1(x, y);
f2(x, y);
}
Upvotes: 2
Reputation: 20878
In C++ there is no way to access locally declared function variables outside of that function's scope. Simply put, what you are asking for here:
I must access variables declared inside another function.
is simply impossible. Anything you try that seems to allow you to do that is undefined behavior.
What you can do is turn "f1" and "f2" as methods of a class and put double a
and int b
as member data states:
class c1
{
double a;
int b;
public:
void f1();
void f2();
};
void c1::f1()
{
// f1 can access a and b.
//some operations
}
void c1::f2()
{
// f2 can see the changes made to a and b by f1
}
This fulfills your two requirements. Namely:
Upvotes: 7