?
Solved

Accessing variables from outside a functions

Posted on 2003-12-09
16
Medium Priority
?
257 Views
Last Modified: 2010-04-01
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
Comment
Question by:lion-g
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +4
16 Comments
 
LVL 10

Accepted Solution

by:
Sys_Prog earned 200 total points
ID: 9902764
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
 
LVL 13

Expert Comment

by:SteH
ID: 9902771
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
 

Author Comment

by:lion-g
ID: 9902948
Hi there,

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

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 17

Expert Comment

by:rstaveley
ID: 9903124
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
 
LVL 8

Expert Comment

by:ssnkumar
ID: 9903232
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
 
LVL 10

Expert Comment

by:Sys_Prog
ID: 9903345
Hi ssnkumar,

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

Amit
0
 
LVL 8

Expert Comment

by:ssnkumar
ID: 9903441
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
 
LVL 17

Expert Comment

by:rstaveley
ID: 9903520
> 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
 
LVL 11

Expert Comment

by:bcladd
ID: 9903560
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
 
LVL 17

Expert Comment

by:rstaveley
ID: 9903684
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
 
LVL 17

Expert Comment

by:rstaveley
ID: 9903973
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
 
LVL 2

Expert Comment

by:xssass
ID: 9963811
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
 
LVL 11

Expert Comment

by:bcladd
ID: 9963892
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
 
LVL 8

Expert Comment

by:ssnkumar
ID: 9970024
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

Technology Partners: 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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses
Course of the Month13 days, 14 hours left to enroll

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question