Saturday 11 November 2017

static - Declaration and Definition of variables in c

itemprop="text">

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


itemprop="text">
class="normal">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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...