1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

out of scope variable running well!!!

Discussion in 'C' started by shyam_oec, Jun 29, 2008.

  1. shyam_oec

    shyam_oec New Member

    Joined:
    Nov 26, 2007
    Messages:
    89
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Software Developer, .NET Framework
    Location:
    Jamshedpur
    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?
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,292
    Likes Received:
    365
    Trophy Points:
    83
    Its not an error in some compiler but try compiling the same in GCC compiler and you should see at least a warning.
     
  3. shyam_oec

    shyam_oec New Member

    Joined:
    Nov 26, 2007
    Messages:
    89
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Software Developer, .NET Framework
    Location:
    Jamshedpur
    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.
     
  4. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,292
    Likes Received:
    365
    Trophy Points:
    83
    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.
     

Share This Page