Tuesday, 27 February 2018

static - Declaration and Definition of variables in c



I understand the terms declaration and definition as below.



Declaration: This is just a heads up to the compiler that a variable of specified "name" and "type" exists in the code. So that it can be defined/assigned at later point of time




Definition: This is the process where an instance of the type is created by allocating a suitable space of memory.



int var; //Declaration and Definition-Agreed!!!
extern int var; //Declaration only ?
static int var; //Declaration only ?


My mind refuses to agree the second and third ones as declaration only statements. Because in many references I see, "extern and static variables are automatically initialized to zero upon memory allocation". And as you see in following code.




#include 
int main()
{
static int i;
printf("%d\n",i);
return 0;
}


The output is 0. So Here it looks like the static int i; is declaration,definition and auto initialization statement. So please add your justification for this



Answer



Objects with static storage duration are initialized by zero in C.



static int a; // initialized by zero
int b; // file-scope, static storage duration, initialized by zero

int main(void)
{
int c; // automatic storage duration, indeterminate value
static int d; // initialized by zero

}


a, c and d are declarations and definitions of objects.



b is a declaration and a definition because there is no other file-scope occurrence of b until the end of the translation unit. Before the end of the translation unit, the declaration is a tentative definition.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...