0

Can anybody tell me the advantages or disadvantages of the following two C code snippets? I have an int x which I need to access from a few functions. Is it better to use it as a reference parameter (Snippet 1) or as a global variable (Snippet 2)?

1st snippet:

struct A {
    int x;
};

void init( struct A * a ) { 
    a->x = 0;
}

void incx( struct A * a ) {
    a->x++;
}

int main(void) {
  struct A a;
  init(&a);
  incx(&a);
  return 0;
}

2nd snippet:

int x;

void init() {   
    x = 0;
}

void incx() {
    x++;
}

int main(void) {
  init();
  incx();
  return 0;
}
GSerg
  • 76,472
  • 17
  • 159
  • 346
hannes
  • 83
  • 5
  • 3
    In 1st case: why'd you need to wrap the `int` in a structure? – Sourav Ghosh May 16 '19 at 08:10
  • 1
    Did you try to use the same functions for 2 different variables? Which variant will work immediately and which won't? – Gerhardh May 16 '19 at 08:11
  • Advantages and disadvantages in what way, using what rules? How do you measure what an advantage and disadvantage? The second code requires significantly less typing, is that an advantage? – KamilCuk May 16 '19 at 08:20
  • 2
    Possible duplicate of [Are global variables bad?](https://stackoverflow.com/questions/484635/are-global-variables-bad) – KamilCuk May 16 '19 at 08:21

1 Answers1

1

When you pass the object reference you can change any object you wish and the function is universal.

int inc(int *v)
{
    return ++(*v);
}

int v;

void foo()
{
    int x;
    int *y = malloc(sizeof(*y));

    struct 
    {
        int x;
        int y;
    }z;

    inc(&x);
    inc(y);
    inc(&z.y);
    inc(&v);
}
0___________
  • 60,014
  • 4
  • 34
  • 74