Variable declaration vs definition

前端 未结 3 1646
深忆病人
深忆病人 2020-12-04 19:55

I was reading some info on externs. Now the author started mentioning variable declaration and definition. By declaration he referred to case when: if a variable is declared

相关标签:
3条回答
  • 2020-12-04 20:27

    During declaration, a memory location is reserved by the name of that variable, but during definition memory space is also allocated to that variable.

    0 讨论(0)
  • 2020-12-04 20:29

    This is how I view it putting together bits and pieces I found on the internet. My view could be askew.
    Some basic examples.

    int x;
    // The type specifer is int
    // Declarator x(identifier) defines an object of the type int
    // Declares and defines
    
    int x = 9;
    // Inatializer = 9 provides the initial value
    // Inatializes 
    

    C11 standard 6.7 states A definition of an identifier is a declaration for that identifier that:

    — for an object, causes storage to be reserved for that object;

    — for a function, includes the function body;

    int main() // Declares. Main does not have a body and no storage is reserved
    
    int main(){ return 0; } 
      // Declares and defines. Declarator main defines                  
      // an object of the type int only if the body is included.
    

    The below example

    int test(); Will not compile. undefined reference to main
    int main(){} Will compile and output memory address.
    
    // int test();
    int main(void)   
    {
        // printf("test %p \n", &test); will not compile 
        printf("main %p \n",&main);
        int (*ptr)() = main;
    
        printf("main %p \n",&main);
    
     return 0;
    }
    
    extern int a;  // Declares only.
    extern int main(); //Declares only.
    
    extern int a = 9;  // Declares and defines.
    extern int main(){}; //Declares and  defines.                                     .
    
    0 讨论(0)
  • 2020-12-04 20:46

    Basically, yes you are right.

    extern int x;  // declares x, without defining it
    
    extern int x = 42;  // not frequent, declares AND defines it
    
    int x;  // at block scope, declares and defines x
    
    int x = 42;  // at file scope, declares and defines x
    
    int x;  // at file scope, declares and "tentatively" defines x
    

    As written in C Standard, a declaration specifies the interpretation and attributes of a set of identifiers and a definition for an object, causes storage to be reserved for that object. Also a definition of an identifier is a declaration for that identifier.

    0 讨论(0)
提交回复
热议问题