DJames
DJames

Reputation: 699

Can I let a C function use external variables, without letting it modify them?

If I have a global variable "x" used by a C function

int foo() {

    extern int x;

    return x;

}

Can I forbid foo from modifying x? I.e. treat x the same way the alternative below would?

int foo(const int x) {

    return x;

}

Upvotes: 0

Views: 59

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 223795

Method One: Const Copy

#define HorribleHackStart(Type, Name) \
    Type HorribleHackTemp = Name; { const Type Name = HorribleHackTemp;

#define HorribleHackEnd \
    }

int foo(void)
{
    HorribleHackStart(int, x)
    ... Here x is an unchanging const copy of extern x.
    ... Changes made to x (by other code) will not ge visible.
    HorribleHackEnd
}

Method Two: Pointer

int foo(void)
{
    #define x (* (const int *) &x)
    ... Here x is effectively a const reference to extern x.
    ... Changes made to x (by other code) will be visible.
    #undef x
}

Comments

I would not use either of these in production code, but they might be useful if you wanted to compile the code to test for violations of the const requirement for x inside the function.

Upvotes: 1

Related Questions