Doubt in variable declaration and definition in C

piyushh

piyushh

@piyushh-O70sb6 Oct 26, 2024
extern int a;
is it a declaration or a definition? the default value for extern type is zero so it can be treated as a "definition"...but why not for
static int a;

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • gaurav.bhorkar

    gaurav.bhorkar

    @gauravbhorkar-Pf9kZD Sep 23, 2011

    When you write extern int a; - it is a declaration not a definition. The extern keyword says that the variable is defined outside the function block.

    The following code will explain this:
    void func( );
    
    void main ( )
    {
        func ( );
    }
    
    void func ( )
    {
        extern int var; //declaring a variable var which is outside the scope of this function (i.e. our global variable)
        printf ("%d", var);
    }
    
    int var = 10; //Defining a global variable. This can be in another file also
    Note that we have declared (and defined) our global variable 'var' outside the func( ) block, and also way below the func ( ).
    Had we defined the global variable 'var' above the func() block, we wouldn't have to declare it using the extern keyword.