Is there a way to reset variables declared as static within a function? The goal is to make sure that the function is not called with lingering values from an unrelated call. For example, I have a function opearting on columns of a matrix.
int foo(matrix *A, int colnum, int rownum){
static int whichColumn;
static int *v; //vector of length A->nrows
if (column != whichColumn){
memset(v,0,size);
whichColumn = which;
}
//do other things
}
The function is called n times, once for each column. Is this a proper way of "re-setting" the static variable? Are there other general fool-proof ways of resetting static variables? For example, I want to make sure that if the call is made with a new matrix with possibly different dimensions then the vector v is resized and zeroed etc. It seems the easiest way may be to call the function with a NULL pointer:
int foo(matrix *A, int colnum, int rownum){
static int whichColumn;
static int *v; //vector of length A->nrows
if (A == NULL){
FREE(v);
whichColumn = 0;
}
//do other things
}
Use an idempotent initializer function and global variables instead.
For example:
int foo;
int *m = NULL;
static void InitVars() {
foo = 0;
if (m != NULL) {
free(m);
}
m = malloc(sizeof(int)*5);
memset(m, 0, sizeof(int)*5);
}
If your initializer is really idempotent, you can call it again to reset the variables.
If you need this to be called automagically, use __attribute__((constructor)) (for GCC) like so:
static void InitVars __attribute__((constructor)) ();
However, you should note that if you need to do this, you should reconsider using in-function static variables and instead use passed-in fresh ones that are returned/written and passed to subsequent related calls.
I'd recommend turning it into a struct and writing a small helper function for managing the semantics of what you're trying to do. It could return the buffer if the request is appropriate for its size, or create a new one on demand (and free the old one) if necessary.
One approach I've seen used when a C module was imported to C++ was to surround the whole module with a class wrapper, and replace all static variables inside functions with uniquely-named "global" varaibles outside the functions. I don't know any good way to achieve a similar effect for projects involving multiple source files, though I'd like to know if one exists. I have some embedded system code in C, which I simulate by adding some C++ wrappers in VS2005. For example, I have I/O registers defined so that something like TX1CON = 0x5C; would translate into something like IOMAP(0x251).P = 0x5C; IOMAP is a property which would send "write 0x5C to address 0x251" to a hardware-simulation program. This approach works well, but I can't do a clean reset. Any ideas?
An approach which can sometimes be helpful if one needs a "reset" method which can hit an unknown number of functions or modules is to have a global counter for how many times that reset method has been called, and then have each function or module include code like:
extern unsigned long global_reset_count;
void do_something(int whatever)
{
static ... this, that, the other, etc. ...;
static unsigned long my_reset_count;
if (my_reset_count != global_reset_count)
{
my_reset_count = global_reset_count;
... initialize this, that, the other, etc ...
}
}
In some multi-threading contexts, if the initialization of the static variables may depend upon some global variables, one may wish to replace the "if" with a "while"; in such a case; memory barriers may also be needed in such a case, though the exact requirements would vary depending upon the operating environment.
Also, an alternative pattern that may be useful within embedded systems would be to have a modules_initialized global variable which gets set to 0 by the global reset method, and then have each module start with something like:
if (!atomic_bit_test_and_set32(&modules_initialized, FOOBOZZ_MODULE_ID))
{
... Initialize module FOOBOZZ ...
}
This would require that there be no more than 32 module ID's, and would require that they be uniquely allocated somehow, but some systems can handle that pretty nicely. For example, a linker may allow one to define a "data section" from address 0-31 of an address space independent from any other; if each module declares a single-byte variable within that address space, the linker could generate the appropriate addresses for those variables.
you could build your function in such a way that if you call it with zero parameters, then it will reset its internal static variables
here is an example :
int foo(matrix *A = NULL, int colnum = 0, int rownum = 0)
{
static int whichColumn;
static int *v; //vector of length A->nrows
if (A == NULL){
FREE(v);
whichColumn = 0;
}
//do other things
}
You actually just have to call function to reset like this:
foo(); // internal values would then be reset
Make sure that all your parameters to the function has default values, if for example you pass an optional, then make sure it has = boost::none as default value
Related
Here's the code:
int EdgeCount = 0;
int numOfEdges = 0;
void addEdge() {
// some code
numOfEdges++;
}
int EdgeWeightArray[numOfEdges]; // error
I want that global array with variable parameters to use it later but I couldn't do that because without #define we can't define globally arrays parameters; and #define is not a variable thing. In my code numOfEdges is variable and I couldn't make it constant.
EdgeWeightArray has global scobe, so it must be a fixed size. But numOfEdges is of course not a constant expression.
What size do you expect EdgeWeightArray to be? Do you expect it to grow when you increment numOfEdges? If so, you nwed to look into dynamic memory allocation; namely malloc and realloc.
Brief example with no error checking:
int numOfEdges = 0;
int *EdgeWeightArray;
void addEdge(some parameters) {
//SOME CODE
numOfEdges++;
EdgeWeightArray = realloc(EdgeWeightArray, numOfEdges * sizeof(EdgeWeightArray[0]));
}
Why not use a global int pointer and allocate memory with malloc() with desired number of elements?
What you are trying to do is not possible because memory for global variables are calculated at compile time and the value of numOfEdges is updated at runtime.
In my eyes, you want to create a not well designed code, where the size has global scope and the vector has to have local scope in order to be stored in the stack (according to your starting point). Anyway, you might do something like that:
void defineSize() {
numOfEdges++;
}
void useIt()
{
int EdgeWeightArray[numOfEdges];
/* Use EdgeWeightArray, once the function has been executed, \
EdgeWeightArray will dissapear */
}
This is an expansion to Jonathons answer.
If you already know how many Elements there will be at maximum for your array you could use a fixed size for your array. This could be faster in the moment, because there is no reallocation happening.
But you have to make sure to do appropriate error handling with this approach. It can be quite error prone.
You would then need a counter to keep track of your Edges, but you appear to already have one of those.
Your code would then look like:
#define MAX_EDGE_COUNT 1000
int EdgeCount = 0;
void addEdge() {
// some code
EdgeWeightArray[EdgeCount] = newEdge;
EdgeCount++;
}
int EdgeWeightArray[MAX_EDGE_COUNT];
Wondering what the differences between the following two bits (labeled Method 1, and Method 2) are, any benefits / risks associated with either, and finally, is there a better way.
typedef struct
{
int iAnInteger;
} s_Thing;
s_Thing sMine;
void SomeFunction(int myInt)
{
/* Method 1 */
s_Thing *pMine = &sMine;
pMine->iAnInteger = 0;
/* Method 2 */
sMine.iAnInteger = 0;
}
As stated, what are the advantages / disadvantages, best practices?
Thanks!
Method 3:
void SomeFunction(int myInt, s_Thing* pWho)
{
pWho->iAnInteger = 0;
}
is even better since will be more maintainable if you make changes to how instances of s_Thing are created.
Your other two methods both suffer from localisation issues: try to limit the number of functions that modify data held at global scope.
Method 1 and Method 2 basically do the same thing, Method 1 just adds an extra level of indirection for no real reason or benefit.
Both methods modify the contents of a global object, leading to tight coupling, re-entrancy and thread safety issues.
The right thing to do is for SomeFunction to take an s_Thing as a writable parameter:
void SomeFunction( int myInt, s_Thing *myThing )
{
...
myThing->iAnInteger = 0;
...
}
which would get called something like
int main( void )
{
s_Thing sMine;
...
SomeFunction( anInt, &sMine );
...
}
As a rule, functions should communicate via parameters and return values, rather than by setting globals. There are times when using a global is
necessary (such as with errno), but life will be easier if you can avoid it.
There is no difference, except readability.
Consider this: if you got struct, which has struct as one of its members, which in turn has a struct as one of its members, which in turn... Well, you got the point.
Then if you need to compare value A with value B of the very inner struct, you'll end up with a line like
Struct1.Struct2.Struct3.Struct4.Struct5.A == Struct1.Struct2.Struct3.Struct4.Struct5.B
Alternatively, you could put
MY_STRUCT* pMeaningfulName = &Struct1.Struct2.Struct3.Struct4.Struct5;
pMeaningfulName.A == pMeaningfulName.B;
which is much more readable and shorter, especially if you have to do many repetitive operations with the same struct.
As far as the rest goes, most compilers nowadays should produce the same code for both methods.
I have my own implementation of C hash_map_t struct that I can use as below?
// string value allocator
allocator_t *str_value_allocator;
allocator_init(&str_value_allocator, string_allocate_handler, string_deallocate_handler);
str_hash_map_init(&str_hash_map, str_value_allocator, 5);
str_hash_map_put(str_hash_map, test_key, test_val, strlen(test_val));
str_hash_map_get(str_hash_map, test_key, NULL)
str_hash_map_remove(str_hash_map, test_key)
str_hash_map_free(str_hash_map);
I would like to use this hash map in function like below:
void handle_keyboard_input(char **tokens, size_t num_tokens) {
char *virtual_key_name = strtok(tokens[1], " ");
size_t num_flags = 0;
char **modifier_flags = str_split(tokens[2], ", ", &num_flags);
// map virtual_key_name (char *) to virtual_key code (int)
// foreach modifier flag (char *) map to modifier flag code (int)
}
I can create 2 hash_maps for key_name -> key_code mapping and flag_name -> flag_code mapping. The problem is that I don't want to create this flag each time the request handler function is called but have only one data structure instance from first call of the function and in successive function invocations I want to reuse this data structure (data store) already created.
My hash_map is created on the heap so there isn't possibility to allocate it like the array somewhere inside library source code file.
In Java or even C++ I could create some Singleton pattern or static member but such concept is not available in C language. Probably I could create this hash_map at program startup somewhere at the beginning of program but how could I pass reference to library used by the program.
My recent idea was to use static hash_map_t variable inside my handle_keyboard_input function and somehow initialised it only when it is NULL (the first function call), and if variable isn't NULL in successive calls just reuse previously initialised hash_map_t structure.
What will be the best approach to this problem?
UPDATE
Could I use such code?
static str_hash_map_t *virtual_keys_map = NULL;
static str_hash_map_t *modifier_flags_map = NULL;
if (virtual_keys_map == NULL) {
virtual_keys_map_init(&virtual_keys_map);
}
if (modifier_flags_map == NULL) {
modifier_flags_map_init(&modifier_flags_map);
}
Since this appears to be a library, you have several options:
You can make your library more "object oriented" and force the user to do the proper instantiation. For example, you would have your ADT struct defined as KeyboardHandler, and then your handle_keyboard_input would look something like this instead:
void KH_handle_input(KeyboardHandler self, char **tokens, size_t num_tokens);
Which means the caller is now responsible for doing the instantiation of that single part:
// caller must get the ADT instance at some point, and you don't care when
KeyboardHandler kh = KH_init();
KH_handle_input(kh, some_tokens, num_tokens);
// some other part can be initialized later
MouseHandler mh = MH_init();
MH_handle_input(mh, some_tokens, num_tokens);
It's possible to create a library initializer for both Windows and POSIX dlls. So you can let this be done automatically instead.
Otherwise, it seems like you will have to make this "check" anytime your functions want to use this potentially-uninitialized hash tables (perhaps it's a single function, but anyway). In which case, I would at least refactor it into a separate function:
void handle_keyboard_input(char **tokens, size_t num_tokens) {
initialize_hashes_if_needed();
// ...and then the rest of the function
}
The reasoning is that you don't want to have to modify several functions if you decide there is something else that needs to be malloced.
Yes, code above cause that pointers will be initialised just once (or if you set them to NULL, condition will be true and it will init again) and stay in memory even if you get outside of function.
The lifetime of function static variables begins the first time the program flow encounters the declaration and it ends at program termination - in other words they are global variables.
Also the name of this variable is only accessible within the function, and has no linkage.
Still need to take great care if you think you need a globally-accessible variable. Read here.
static str_hash_map_t *virtual_keys_map = NULL;
static str_hash_map_t *modifier_flags_map = NULL;
if(virtual_keys_map == NULL) {
virtual_keys_map_init(&virtual_keys_map);
}
if(modifier_flags_map == NULL) {
modifier_flags_map_init(&modifier_flags_map);
}
I have an application where the arguments list cant be reeeealy long. I can run my app like this:
./app -operations a b c d e f g h i j ...
And so on. My a,b,c ... are algorithms which I would like to run (functions defined in my code). To be able to execute them, I have something like this:
if(a)
funA();
if(b)
funB();
if(c)
funC();
...
It does not look nice, does it? I must say, there's much more calls than just 26, since my application grows and grows, my arguments list grows too. I'm looking for a fancy way to make it simpler/prettier. Is it possible, anyone with an idea?
I dont want to use C++ nor external libraries for making it simpler. Can it be done in pure C?
Here is a very simplified possible option:
#include <stdio.h>
// create a common structure to hold all your
// function parameters;
typedef struct Parameters
{
int p1;
int p2;
} Param_Type;
// sample function 1
void func1( Param_Type *params ) {
printf("hi from func1: %d\n", params->p1 );
}
// sample function 2
void func2( Param_Type *params ) {
printf("hi from func2: %d\n", params->p2 );
}
int main() {
Parameters p;
// parse the command line and populate the parameters struct;
p.p1 = 1;
p.p2 = 1;
//create a lookup table with pointers to each function.
void (*F_A[2])(Param_Type *) = {func1, func2};
//You will still need some function, that given a set of arguments, can
// derive and return an index into the array that maps to the correct
/ function.
int func_idx = your_mapping_function(...) // todo
// dispatch the correct function call.
(*F_A[func_idx])(&p);
return 0;
}
You can use use getopt() to read the command line parameters.
And I don't see any optimization in the way you are deciding what action to take depending upon the arguments. I'd say it's just a bad design of doing things. You could try changing your approach.
You could use enums and function pointers to define handlers for every different set of arguments.
Something in the lines of:
typedef enum {
ARG_A,
ARG_B,
ARG_C,
// etcetera
MAX_ARGS
} CmdArgId;
bool cmdArgStates[MAX_ARGS];
typedef void (*CmdHandler_f)();
CmdHandler_f cmdHandlers[MAX_ARGS] = {
// TODO: set function pointers
};
int main()
{
// set cmdArgStates[] indexes to true or false,
// according to the program command line.
ParserCmdArgs();
for (int i = 0; i < MAX_ARGS; ++i)
{
if (cmdArgStates[i] == true)
{
cmdHandlers[i]();
}
}
}
If you need the handler functions to have different numbers of arguments, you can define a common function with a fixed number of args and just ignore them when they are not needed. I.e.: typedef void (*CmdHandler_f)(); could also de something like typedef void (*CmdHandler_f)(int, int, int);
One idea would be to create a structure that can be used to abstract each command line option. Here is a possible method you could use to implement that idea :
Create a structure that can represent each function you need to
support, and have it hold a pointer to the function and a string for the search key.
Create an array of this structure and initialize the members accordingly
Use an algorithm, such as a binary search, to find the key in the structure array when looping through the command line arguments.
Once you have the structure from the key, you can then call the function which will handle the behavior desired in the option.
It's possible this won't apply to your situation, but this really is an implementation specific problem. If you want a more specific solution, you should probably post more details about your functions and the implementation behind them.
I use gcc (gnu99) under linux.
Assume I have a simple function that computes (say, prints) some values.
To fix ideas without resorting to factorial, let me propose this little toy function:
void rec(int val, int nd)
{
val *= 10; nd++;
for (int u=0; u<=9; u++, val++)
if (val && 0==(val%(nd*nd)))
{
printf("%d\n",val);
rec(val,nd);
}
}
which called as rec(0,0), will print the 86 positive numbers with the property that every their prefix of length k is divisible by k^2 (largest is 6480005).
Q: is there a standard way to turn it into a routine which can be called repeatedly and each time returns a new value until it signals in some way that there are no more values ?
In practice, I need a way to call rec(), getting back a value, and then be able to resume execution from where it was, to get next value and so on.
I thought about using a combination of setjmp(), longjmp(), setcontext() and the like, but the examples on these topics confused me a little.
Thanks.
Without resorting to setjmp() and its likes, I would think of two possibilities to achieve your objective.
Define a structure and functions that operate on it
You can define a structure that contains the state you are interested in:
struct S {
int * numbers;
size_t length;
size_t current;
}
and a set of functions that operate on it:
// Basically your rec(val,nd) function
int initialize(int val, int nd, S* s);
// Get the next value
int getNextValue(const S* s);
...
// Free memory
void Sfree(S* s);
Embed a state into your own function
In this case you embed a persistent state (using some static variable) directly into your function rec(). Being persistent this state will be preserved across different calls to the function, and permit you to keep track of how many times the function was called and of any other information you may need. Beware that this solution requires a particular care if used inside multi-threaded environments.
In C++ this is done via a class that holds a the state (variables).
In C, the preferred method of operation is to pass this state or context to the function.
Do not use a global state as later on you'll find that it causes too many issues.
Example:
int foo(struct fooContext* c, int arg1, int arg2) {
}