Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable does not take new value

Tags:

c

I was making a simple C program

#include<stdio.h>
static int a;
a = 5;
int main()
{
printf("%d",a);
return 0;
}

Compiler error: "non static declaration of 'a' follows static declaration"

What does this error mean?

like image 435
mrigendra Avatar asked Dec 04 '22 06:12

mrigendra


2 Answers

what this error log means?

It is a little tricky: what looks like an assignment

a = 5;

is treated as

int a = 5;

due to an old C rule that allowed you to declare int variables and int-returning functions without specifying their type explicitly (this is definitely not a good idea in the modern version of C).

Note that this is treated as a declaration with an implicit int only in the scope outside a function body.

You can fix it by combining the declaration with initialization, like this:

static int a = 5;
like image 93
Sergey Kalinichenko Avatar answered Dec 22 '22 17:12

Sergey Kalinichenko


Outside a function you can only declare variables, you cannot have actual code statements.

a = 5;

is being interpreted as another declaration, when your intent I think is to write some code.

instead declare and initialise a at the same time

 static int a = 5;
like image 37
djna Avatar answered Dec 22 '22 16:12

djna