• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 260
  • Last Modified:

Accessing variables from outside a functions

Hi experts,

I am a beginner in C++ programming and I need help on accessing variable from outside a function.

I have this function,

 void testing(void)
{ int time;
int accuracy;
...
...
...
...
...
}

int main (........){
int timemain;
int accuracymain;


testing();
// I need to store the time and accuracy of testing in a variable in main
how do I do it ?

Thanks and regards,
C++ Beginner

0
lion-g
Asked:
lion-g
  • 4
  • 3
  • 2
  • +4
1 Solution
 
Sys_ProgCommented:
You can pass the variables in main by reference to the function

example

void f ( int &var1 ) {
  var1 = 2 ;
}

int main ( ) {
  int myvar1 ;
  f ( myar1 ) ;
}

The above code would give print 2
Soimliarly, u can have your two variables passed
0
 
SteHCommented:
What is the reason for that? Are time and accuracy modifed in fn testing and you just want to know its last values in main as well?
void testing (int& mtime, int& macc)
{

mtime = time;
macc = accuracy;
}

and call it in main like

testing (maintime, mainaccuracy);

You need to pass variables to the function testing which can hold the values of the function variables. Outside of the function these variables don't exist anymore and you can't access them.
0
 
lion-gAuthor Commented:
Hi there,

time and accuracy are calcualted in the function.
They are needed to do other calcuation as well outside the function.

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
rstaveleyCommented:
timemain and accurrancymain have been declared as automatic variables in the main function. If you want them to be altered by a function, you can use pass a references to the variables in function paremeters, as previously indicated. If you find yourself passing them to everyting under the sun, you might consider declaring them as globals... and to prevent the C++ thought police from telling you how wicked you were poluting the global namespace... you could put them into a suitable namespace.

e.g.

   namespace my_timing {
      int time;
      int accuracy;
   }
0
 
ssnkumarCommented:
You can declare them outside main (global variables) and update them in the called function. The changes will be visible in main also then! And you can use and modify them in any other functions belonging to this program.
0
 
Sys_ProgCommented:
Hi ssnkumar,

Using global variables is not a good practice and should be avoided as much as possible

Amit
0
 
ssnkumarCommented:
Yes, I know that and I also subscribe to that idea.
But, for a beginner in C++, it is the easiest way to get started. And once he is comfortable with C++, then he can learn safe ways, good ways, efficient ways etc:-)
0
 
rstaveleyCommented:
> Using global variables is not a good practice and should be avoided as much as possible

I'd argue that it is OK to do it as long as you feel bad, when you do :-)

I'd also argue that you should feel less bad, if you put them in namespaces. That makes them about as acceptable as public static member variables, anyhow.
0
 
bcladdCommented:
Okay, global variables can be used and a namespace makes one feel less dirty about doing it. Point taken BUT this is exactly the case where global variables are the WRONG answer.

lion-g states that time and accuracy are "calcualted in the function" and are needed outside the function. The suggestions to return the values in reference variables is the right answer because it connects the calculation of the variables (in the function) with the setting of the variables (in the call to the function) and, hopefully, with the using of the variables. If a function has a side-effect of setting global variables that decouples the setting and the using in a very dangerous way. What if someone down the line doesn't remember the side effect (should be documented all over the place but still) an moves the first call to test AFTER the first use of the variables in main?

Passing values back from the function would make their being set much more obvious at the point of call.

Not sure what test does but this might be a candidate for encapsulation inside of a class. Put the two variables in as data members with accessor functions, have the constructor call test (an internal function that sets the values of the member function) and then have accessor functions for time and accuracy. Your accessors can also call test if there is a need to recalculate the values.

Earlier suggestions about pass by reference are the easiest answer that doesn't lead to the worst kind of use of global variables.

Hope this helps,
-bcl
0
 
rstaveleyCommented:
I agree whole-heartedly with what bcladd says, here. It isn't a good contender for a global. You are really looking for a work-around for C++'s inability to return two values from a function.

References are a convenient tool for this in C++. You can also use a std::pair<> to return two values.

e.g.
--------8<--------
#include <iostream>
#include <utility>

typedef std::pair<int,int> int2;
int2 testing();

int main()
{

        int2 results = testing();
        int time = results.first;
        int accuracy = results.second;
        std::cout << "Time " << time << ", accuracy " << accuracy << '\n';
}

// Return time and accuracy as an int2 pair
int2 testing()
{
        int time = 1;
        int accuracy = 2;
        return int2(time,accuracy);
}
--------8<--------
0
 
rstaveleyCommented:
NB: bcladd's suggestion to encapsulate the results in a class is more self-explanatory than std::pair. In the calling code, you don't need to know that time is the first in the pair and accurrancy the second.
--------8<--------
#include <iostream>

// Constructor does the job of testing()
struct Results {
        int time,accuracy;
public:
        Results();
        int getTime() const {return time;}
        int getAccuracy() const {return accuracy;}
};

int main()
{
        Results results;
        int time = results.getTime();
        int accuracy = results.getAccuracy();
        std::cout << "Time " << time << ", accuracy " << accuracy << '\n';
}

// Results constructor - we use this to initialise the test results
Results::Results()
{
        time = 1;
        accuracy = 2;
}
--------8<--------
0
 
xssassCommented:
You should be able to get the value of timemain and accuracymain in the function testing
by preceding them with 2 double points...

So by typing ::timemain and ::accuracymain.

Hope this helps
.K.
0
 
bcladdCommented:
xssass-

The global scope operator permits access to GLOBAL names. Note that names declared INSIDE of any function (main is just a function) are NOT global. Moving their declaration outside of main would change their fully qualified names to ::timemain or whatever; so long as they are inside a function they are NOT visible in any other function.

One reason for using the global scope operator is to access global names that are masked by local names. Imagine there is a global variable gTime and a local variable in test called gTime. How could you access the global gTime INSIDE test?

int gTime = 99;

int test() {
  int gTime = -1;

  // I want to print the value of the global gTime...what can I do? If I just say cout << gTime I get the -1...use the global scope operator:

  cout << ::gTime << endl;

  return 0;
}

Note that masking names is bad practice but it can happen with intervening class/namespaces that use common names that would be difficult to change.

Hope this helps, -bcl
0
 
ssnkumarCommented:
lion-g,

So many expert comments are logged in.....
But, you have not given a single feedback! Without that, it will be difficult to proceed!
If you have somehow found the answer by yourself, then close the Q.

-ssnkumar
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
  • 2
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now