Reputation: 235
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;
}
Upvotes: 3
Views: 10582
Reputation: 6465
Static variable
static Event * ptr = NULL;
cannot be seen from other source file, but if you pass it as argument, it is just copied on stack same as other pointers, so you can do it that way.
But i would pass it as const
pointer and explicitly document it that it is static
variable for others.
void function2(Event * const pointer)
{
pointer->event = 2;
}
Upvotes: 3
Reputation: 67999
You can do whatever you want with it. Static means global storage && local file symbol visibility. But variable can be used as you wish
Upvotes: 2
Reputation: 1319
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.
Upvotes: 3