is the definition of declaration is contradictory?????????

S

sushant

according to the definition of declaration of a variable "the variable
is not allocated any space in the memory till it is defined".

so the code:

int main(void)
{
int x,*p;
p=&x;
printf("%p",p);
return 0;
}

should generate an error bcos x is only declared not defined... but
after executing the above code it was showing some address. the story
is not yet finished... after initialising x with some value , it was
showig the same address....
any answer for that....
 
R

Richard Bos

sushant said:
according to the definition of declaration of a variable "the variable
is not allocated any space in the memory till it is defined".

so the code:

int main(void)
{
int x,*p;

Yech - Google-unindented code!
p=&x;
printf("%p",p);
return 0;
}

should generate an error bcos x is only declared not defined...

Wrong. That's not just a declaration of x (and p), it's a definition as
well. If you want to declare, but not define, a variable, declare it
using extern.

(BTW, for fully conforming code, you should cast that pointer to void *
before printf()ing it using "%p".)

Richard
 
L

Lawrence Kirby

sorry for that unindented code, but its not mentioned any where that
for declaration we have to use extern keyword. i just want to declare a
local variable for that matter ...... now what??

C does not permit you to just declare local variables, all such
declarations are also definitions. Why would you want to?

Note that you can declare something like:

int main(void)
{
extern int x;
...
}

Here the scope of this declaration (which is not a definition) is local
to the block but the variable x isn't, this declaration will be "linked"
with other declarations and definition of x in the entire program that
have external linkage. E.g. if the following is in the same program, not
necessarily the same source file

int foo(void)
{
extern int x;
}

then the x in this function refers to the same object as the x in main().
There needs to be a definition for x somewhere but that has to be at file
scope, it cannot be within a function.

Lawrence
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top