Search code examples
cvariables

Exchanging information between functions in C


I'm writing program in C, that goes with structure like this:

int main() 
{
 while(true)    
  {
   mousecommands();
   graphicupdate();
  }
}

Where each step in main is void function. Simplified task that I want to achieve is:

  1. mousecommands() detects where mouse is
  2. graphicupdate() draws circle in that position.

To do this I need way to pass information from one function to another.

How should I do it?
Easier way would be global variables.
More clean would be to use variables in main and give pointers to them as arguments to each function. This is fine when each function passes information containing in variable or two, but not in twenty or so.

Thanks for all advice, cheers


Solution

  • To illustrate @i486 comment:

    struct MouseInfo { /* 7 members */ };
    struct DisplayInfo { /* 16 members */ };
    struct KeyboardInfo { /* 3 members */ };
    struct AllInfo {
        struct MouseInfo *m;
        struct DisplayInfo *d;
        struct KeyboardInfo *k;
    };
    

    then pass around pointers to relevant structs, maybe to struct AllInfo if required.

    int main(void) {
        struct AllInfo *a = initAll();
        mouse(a->m);
        circle(a->d, a->m);
        AllRelease(a);
    }