user225312
user225312

Reputation: 131627

Definition and declaration of variable with a value

Just started with K & R and on the 2nd chapter, there is the line:

Declarations list the variables to be used and state what type they have and perhaps what their initial values are.

So:

int x = 42 is a definition.

and int x is a declaration but also a definition since every definition is a declaration.

But when we assign an intial value like K & R say, doesn't that make the declaration a definition?

Upvotes: 1

Views: 928

Answers (2)

dtech
dtech

Reputation: 14060

You confuse two things:

  1. A declaration states (declares) what an object's* type, name and scope is
  2. A definition defines what a object's content is

* object as in: variable, function etc., not an OOP object.

A definition is hence very often also a declaration, since you cannot define what is in an object when you do not state what the type of the object is. Easiest to remember is just: "Every definition is a declaration, but not every declaration is a definition"

For variables

There is only 1 way to declare without defining the variable:

extern typeX variable_name

This tells the compiler that there is a variable called variable_name with type typeX, but not where to get it. Every other way to declare a variable is also a definition, since it tells the compiler to reserve space for it and perhaps give it an initial value.

The difference is much clearer in structs and functions:

For Structs

A declaration:

struct some_struct{
    int a;
    int b;
}

This declares some_struct to the compiler with a and b as struct variables both with type int.

Only when you define them space is reserved and you can use them:

void foo(){
    struct some_struct s;
    s.a = 1; // For this to work s needs to be defined
}

For functions:

The difference is much more clear

declaration:

// This tells the compiler that there is a function called "foo" that returns void and takes void arguments
void foo();

A definition could be like the one above (in the struct part)

Upvotes: 2

king_nak
king_nak

Reputation: 11513

Basically you can say that a declaration simply tells the compiler that there is somewhere a variable with that name and type. It does produce any code, and in C, this has to be done with the extern keyword on variables. Function prototypes (without implementation) are also mere declarations, and don't need the extern keyword, but you can still provide it. A definition produces code, e.g. allocates memory on the stack or heap for a variable, or the body for methods.

In that sense, both of your statments are definitions, and any definition is also a delcaration.

I think that might by a mistake by K&R...

Upvotes: 1

Related Questions