Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing static variable to function

Tags:

c

I have a ptr variable that is updated in a function. I want to pass this variable to function2, which is in a different .c file. Is it legal to pass a static variable to a function not in the same .c file? Would it be safer to just keep a global ptr without static keyword?

static Event * ptr = NULL;

void function(Event * newPtr)
{

   ptr = newPtr;
   function2(ptr);
}

//in separate c file
void function2(Event * pointer)
{
    pointer->event = 2;
}
like image 889
Smiley7 Avatar asked Feb 13 '26 22:02

Smiley7


1 Answers

static specifier only limits the scope of the variable (internal linkage). But when you pass the ptr, the address contained in ptr will be used and that is completely legal (no problem in compilation, since you are not using the variable ptr, you are using the value contained in it).

But think twice before doing that since you declared as static if some other person looks at your code, its gives an impression that the variable is used only in this file. If the code in function2 does anything to the passed pointer (assume you have dynamically allocated memory to your pointer and it is freed in function2 and you tried to delete/access in your file where you declared ptr).

If you take care of what function2 is about to do with the pointer, then its completely safe to do so. But as I mentioned above, it is not a good practice to do so.

like image 102
infinite loop Avatar answered Feb 15 '26 11:02

infinite loop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!