some observations need explanation

Discussion in 'C' started by hitesh_best, Aug 5, 2007.

  1. hitesh_best

    hitesh_best New Member

    Joined:
    Aug 3, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Hello friends,
    I am a newbie,
    Just did some simple experiments but found some weird observations.

    Lets see this code
    Code:
    main()
    {
      int i;
      printf("%d",i);
    }
    

    Yes I have not initialized the variable 'i'
    This code gives output 0

    lets see this code
    Code:
    main()
    {
      int i;
      --i;
      printf("%d",i);
    }
    
    This code gives answer 813;

    Why this the output 813, when the initial value in variable i is 0;

    and have a look at this code
    Code:
    main()
    {
      int i;
      printf("%d",i);
      getch();
    }
    
    Now this code does not give output as 0 but it gives -28710

    Code:
    main()
    {
      int i;
      --i;
      printf("%d",i);
      getch();
    }
    
    Now this code gives the output 841.


    Even using the function clrscr() give different results.

    Can anuone explain these observations,

    Thanks a lot
     
  2. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    Sure. But since you know that i is uninitialized and you're farbling with it anyway, you won't be satisfied. Your code results in what the standard describes as undefined behavior.

    Your time would be much better invested in learning the language properly. If that's boring, at the moment, perhaps you should READ the standard.

    Now, if you'll excuse me, I'm going to go bombard various parts of my body with random levels of radiation. Should be an interesting experiment.
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    You try printing the address of i in each run of your program and see what is the value at that location and you will get the answer to your query.
     
  4. vignesh1988i

    vignesh1988i Banned

    Joined:
    Sep 19, 2009
    Messages:
    72
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    Chennai
    Good morning ,

    since you have not implicitly given the value of 'i' or u have not initilized 'i' , so in 'i' every time u run the program , this 'i' will contain different garbage values.........

    thank u:pleased:
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice