Search code examples
cpointersextern

Can't assign variable to an extern'd variable in C


Why does this not work

extern int externed_variable;
int variable = externed_variable;

While this does

extern int externed_variable;
int *variable_ptr = &externed_variable;

The compiler error I get from the former is "expression must have a constant value". I am using MSVC.


Solution

  • "expression must have a constant value"

    As the error says, When you initialize a variable, it should be constant.

    In this case,

    extern int externed_variable;
    int variable = externed_variable;
    

    You are initializing with a "variable" and variable gets value run-time.

    But when you do this:

    extern int externed_variable;
    int *variable_ptr = &externed_variable;
    

    You are assigning address, addresses for global variable are decided at Compile time and hence, Constant. And you are allowed to init a variable with constant value.

    So to answer you, As Addresses for global variables are assigned during compilation and are constant, you won't get error!