Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What are the benefits and drawbacks of making a function that returns a pointer to a static global variable from another object file?

I am thinking of doing this because it suits my compartmentalization ideas, so I am trying to figure out if it is a good idea performance-wise.

// obj1.c
static char *data;

char* return_pointer_for_data() {
    return data;
}

// obj2.c
static char *buffer;

void copy_data_to_buffer(char* ptr) {
    buffer[5] = ptr[5];
}

// main.c
copy_data_to_buffer(return_pointer_for_data());

I would like to know the benefits and drawbacks of doing return_pointer_for_data(), and how common this approach is. The other approach I am thinking of is:

// obj2.c
void copy_data_to_buffer(char* ptr1, char* ptr2) {
    ptr1[5] = ptr2[5];
}  

// main.c
char *data;
char *buffer;
copy_data_to_buffer(buffer, data);

I have gotten answers about access speed comparison for copying data, ranging from "it highly depends" to "it doesn’t matter", so I decided to base my decision on the benefits and drawbacks of return_pointer_for_data().

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Benefits:

  1. Easy to share data over functions, you don’t have to pass a char* every time you call a function.

Drawbacks:

  1. If your program has multiple threads, it might result a race condition because multiple threads can write to it at the same time. You have to use a lock to protect it.
  2. It can make your code hard to maintain when it grows. You need to careful order your function calls because they might need other function to set up the global variable.

Performance does not matter too much in this case, the first approach has an overhead of a function call.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading