Declaring vs defining variables in c

This question already has an answer here:

  • What is the difference between a definition and a declaration? 25 answers

  • Does the compiler set aside memory for the declared (but not defined) variables?

    No, compiler just take a note of this variable name and type. No memory is allocated for declaration.

    int i; can behave as definition if i is used (not optimized out) and no other definition of i is present in any other compilation unit and storage will be reserved for it. (because storage is reserved for definitions)


    Definition is when storage is allocated for a variable. Declaration does not imply storage has been allocated yet.

    A declaration is used in order to access functions or variables defined in different source files, or in a library. A mismatch between the definition type and the declaration type generates a compiler error.

    Here are some examples of declarations that are not definitions, in C:

    extern char example1;
    extern int example2;
    void example3(void);
    

    From the C standard (n1256):

    6.7 Declarations
    ...
    5 A declaration specifies the interpretation and attributes of a set of identifiers.

    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;101)
    — for an enumeration constant or typedef name, is the (only) declaration of the identifier.

    "Does the compiler set aside memory for the declared (but not defined) variables?"

    No. Compiler only allocates memory for (at time of) variable definition, not on variable declaration.

    You can better understand the logic using a simple analogy, multiple declaration is allowed for a single variable, but multiple definition is not.

    链接地址: http://www.djcxy.com/p/40622.html

    上一篇: 在C ++中声明C == define?

    下一篇: 在c中声明vs定义变量