int a; is Definition and Declaration both ? or declaration only ?

Recommended Answers

All 7 Replies

int a; is a declaration as well as definition. This c statement not only says the type of the variable but also allocates the memory required for this variable.

how shd i do only declaration then !!
extern int a; ???
is this right !!

how shd i do only declaration then !!
extern int a; ???
is this right !!

Yes. extern keyword tells to compiler that variable 'a' is defined somewhere else, i.e. with 'extern' we only do declaration of variables. And Definition = Declaration + Memory allocation + Initialization (sometimes) ,- such as int a ;

thanks for replying !
int *p;
p gets declared and defined;
then why do we have to give memory dynamically ??
p=(int*)malloc(sizeof(int)); ??

thanks for replying !
int *p;
p gets declared and defined;
then why do we have to give memory dynamically ??
p=(int*)malloc(sizeof(int)); ??

No, p is not defined until you do one thing of :
1. reserve some new memory block for it. (for example with malloc()).
2. define p to point to some existing memory block, such as:

int x = 7;
int* p = &x;

@0x69:
What I understood was that you state that the following isn't a definition: int *p; .

http://web.archive.org/web/20050207005628/http://dev.unicals.com/papers/c89-draft.html#1.6:

"Object --- a region of data storage in the execution environment, the contents of which can represent values. Except for bit-fields, objects are composed of contiguous sequences of one or more bytes, the number, order, and encoding of which are either explicitly specified or implementation-defined."

From this I conclude that a pointer variable is an 'object'.

http://c-faq.com/sx1/index.html:

"Definition --- A declaration of a variable or function which allocates and optionally initializes (in the case of a variable) or provides the function body (in the case of a function). A definition in this sense is the opposite of declaration, sense 2. See question 1.7. 2. A declaration of a structure, union, or enumeration type which describes the type (and usually assigns a tag) without necessarily defining any variables of that type. 3. A preprocessor #define directive."

Applied to pointer variables: since storage for holding a memory address is allocated and since initialization of the variable is optional, I would conclude that int *p; is a definition.

Hm... it depends How we will define "definition". If it is defined like you said - then yes, you are right, p is defined and object to which p points to is undefined. But in general case it is unreasonable to argue on definitions cause same thing can be defined in many ways. And there are no clear way to distinguish which definition is better than the other.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.