Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

c - Variable declaration vs definition

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 the space for it is not allocated. Now this brought me to confusion, because I think MOST of the times when I use variables in C, I am actually both defining and declaring them right? i.e.,

int x; // definition + declaration(at least the space gets allocated for it)

I think then that only cases in C when you declare the variable but not define it is when you use:

extern int x; // only declaration, no space allocated

did I get it right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...