Declarations, definitions, initializations in C, C

2019-02-12 15:20发布

问题:

What do the terms mean in each of the above languages? Why do the languages differ (wherever they do, if at all they do) in this respect?

回答1:

C/C++:

A declaration is a statement that says "here is the name of something and the type of thing that it is, but I'm not telling you anything more about it".

A definition is a statement that says "here is the name of something and what exactly it is". For functions, this would be the function body; for global variables, this would be the translation unit in which the variable resides.

An initialization is a definition where the variable is also given an initial value. Some languages automatically initialize all variables to some default value such as 0, false, or null. Some (like C/C++) don't in all cases: all global variables are default-initialized, but local variables on the stack and dynamically allocated variables on the heap are NOT default initialized - they have undefined contents, so you must explicitly initialize them. C++ also has default constructors, which is a whole nother can of worms.

Examples:


// In global scope:
extern int a_global_variable;  // declaration of a global variable
int a_global_variable;         // definition of a global variable
int a_global_variable = 3;     // definition & initialization of a global variable

int some_function(int param);  // declaration of a function
int some_function(int param)    // definition of a function
{
    return param + 1;
}

struct some_struct;  // declaration of a struct; you can use pointers/references to it, but not concrete instances
struct some_struct   // definition of a struct
{
    int x;
    int y;
};

class some_class;  // declaration of a class (C++ only); works just like struct
class some_class   // definition of a class (C++ only)
{
    int x;
    int y;
};

enum some_enum;  // declaration of an enum; works just like struct & class
enum some_enum   // definition of an enum
{
   VALUE1,
   VALUE2
};

I'm not as familiar with the other languages you asked about, but I believe they don't make much of a distinction between declarations and definitions. C# and Java have default initialization for all objects - everything is initialized to 0, false, or null if you don't explicitly initialize it. Python is even more lax, since variables don't need to be declared before they're used. Since bindings are resolved at runtime, there's no real need for declarations of functions, either.