My goal is to make a static variable 'val' available to a different .c file (just for experimentation) .

so i made a global pointer which holds the address of the static variable, and by this global pointer, i am trying to access the static variable's value in another file .

But,

static int val=33;
int *ptr;
ptr = &val;

gives me error.

while if i do it like this, it works .

static int val=33;
int *ptr = &val;

Why?

2 Answers

2
bruno On

doing

static int val=33;
int *ptr;
ptr = &val; /* define a global variable with an init value */

at global scope you define global variables and for the compiler the implicit type of ptr is int in the line ptr = &val; so this is not compatible with an int*. You cannot have an assignment at global scope, this is why ptr = &val; is not the assignment of ptr previously defined but the definition of a global variable with an initial value.

Putting the code in a local scope there is no problem, for instance with

int main()
{
  static int val=33;
  int *ptr;
  ptr = &val; /* an assignment of ptr */
}

compile without problem

1
Eric Postpischil On

You are using an old or poor quality compiler which assumes int for a missing type.

At file scope, an expression statement such as ptr = &val; is not part of standard C. The compiler is attempting to treat this as a declaration statement. To do that, it assumes a type of int, as if the statement were:

int ptr = &val;

Since ptr was previously declared int *, this new declaration with type int conflicts, and the compiler reports there are conflicting types.

C 2018 6.7.2 2 specifies a constraint for declarations:

At least one type specifier shall be given in the declaration specifiers in each declaration, and in the specifier-qualifier list in each struct declaration and type name.

When a constraint is violated, a compiler should issue a diagnostic message about it. So a good compiler will warn that the type specifier is missing (and not just that the resulting default type conflicts with a prior declaration).