Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   out of scope variable running well!!! (http://www.go4expert.com/forums/scope-variable-running-t11727/)

shyam_oec 29Jun2008 22:02

out of scope variable running well!!!
 
int *dangle(int num)
{
int temp=5;
return(&temp);
}

void main()
{

int *iptr,deng=56;

iptr=dangle(deng);
printf("%d",*iptr);
}

I read that this code is not correct,since iptr is being assigned address of a
variable which losses it's scope when control reaches back to main,i.e temp variable
is lost.
BUT when i compiled and ran this code it produced no error,rather it gave output
5!!!.here every thing seems all right,then why it has been said that it's wrong?

shabbir 30Jun2008 09:20

Re: out of scope variable running well!!!
 
Its not an error in some compiler but try compiling the same in GCC compiler and you should see at least a warning.

shyam_oec 30Jun2008 10:21

Re: out of scope variable running well!!!
 
then what will be the most appropiate answer if this question is asked in exam?In book
i have read it's wrong but actual compilation works well..plz give a solid answer.that what
is happening.

shabbir 30Jun2008 12:35

Re: out of scope variable running well!!!
 
The address which you are passing is not overwritten. Try giving a printf() or call some other function before printing the output and share your output.


All times are GMT +5.5. The time now is 11:43.