Is it possible declare a global variable from within a function?
Why would I wanna do this, you ask? Why not just declare it globally?
Two reasons:
Technical Reason - This function requires that data be saved (and operated on) between calls:
Example:
void ExampleFunct(double InputArg)
{
double LiveData;
/*NEEDS TO BE GLOBAL ---> */ double SumData;
LiveData = InputArg; //-- input argument is real-time data
SumData = SumData + LiveData //-- SumData is a running total
}
Problem is, if "SumData" is declared locally, it re-initializes every time the function is called, dumping all memory and resetting it, and my driver program calls this function thousands of times! It works as intended if I declare "SumData" globally but that leads me to reason #2....
Functional Reason - The driver programs I write makes use of many of the same functions, which I have written as well, in one combination or another. I have built these common functions into a library that I simply declare up-front and use my functions by simply calling them. There is no need to copy and paste the actual code for each function below my "main()" code or declare any variables other than those of the input arguments. Its a much more practical and efficient way of doing things, I simply call the function, pass it some arguments and get what I need. The problem Im having with the above function is that I cannot simply do that..it doesn't "just work".. every time I use it in a new driver program I need to accommodate it by declaring a bunch of global variables. Kinda silly, I know, but I prefer a more elegant style to an ad-hoc one.
Unfortunately, I a noob and cant find a solution to this issue other than just biting the bullet and declaring the needed variables globally, but there MUST be a way around this.
Right after I posted this I had the idea of adding the above mentioned function to my library and declaring the needed variables globally within the library, and it worked!! Now I can call my function within my driver program simply by passing it arguments :)
I would still appreciate any replies you have on whether declaring global variables from within a function is possible..
so I ran into a problem: the way this program functions is by running the driver program over and over which in turn calls my functions over and over (its an optimization program). having declared the variables as "static" it definitely solves the problem of them being de-initialized between function calls but they DO need to be de-initialized between driver program runs. So now every time I run my software, each time the driver runs, it adds the results to that of the previous run, and so on and so on....
Is there any may I can have these variables appear global from the perspective of the function but local with respect to the driver program itself? Im starting to think its asking too much :-/