1

A.c

static int var;

int* getVar(void)
{
    return &var;
}

A.h

int* getVar(void);

B.c

#include "A.h"
int main(void)
{
    int* ptr = getVar(void);
    *ptr = 3;

    return 0;
}

As title. Can I manipulate file-scope variable var via a pointer within other file?

Thanks.

2 Answers 2

1

This is perfectly valid. Whether it is a good idea is a separate matter (and it might be, in some particular cases).

As long as the object that the pointer points to still exists when you dereference it, the access is valid. Since this is a global variable, the pointed object (i.e., the static int var variable) will always exist, and thus the access is completely valid.

Sign up to request clarification or add additional context in comments.

7 Comments

Can I close this question? Because you both gave me an answer
I'm not sure it's a good idea to think of any variable being 'global' in C (at least not in code that involves more than one translation unit). The maximum scope you can achieve is the translation unit; anything beyond that either requires explicit extern declarations, (or repeated definitions if working with gcc and the -fcommon flag on), in every single translation unit that wants to have access to the "global" variable. And using static will inhibit exactly that.
@AndyLin Questions aren't "closed" in SO. You can mark one of our answers as "accepted", whichever one answers your question better. That's when the question is considered answered. But questions aren't actually closed unless they violate the rules.
@GermanNerd I think you're mistaking global lifetime (i.e., not constrained to a scope) with global visibility (i.e., accessible from any part of the code). The former is guaranteed by declaring the variable outside of any function; the latter is impossible in C. Globals usually refer to the former, for this very reason.
@aaaaaa123456789 You comment underlines my concerns: You (and you are not alone) have it the wrong way round. Looking at the C11 standard, global is only mentioned in conjunction with floating-point flags. In 6.2.4 the standard talks about storage duration and lifetime: No mention of global. C itself has no global keyword. So let's look at wiki: ... a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program..., which is exactly how this has been used for decades. ....
|
1

Yes, you can manipulate var via pointer within other file because variable var has static storage duration and objects with static storage duration live for the lifetime of the program.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.