Doubt in the output

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • saiavinashiitr
    New Member
    • Mar 2014
    • 16

    Doubt in the output

    Code:
    #include <iostream>
    using namespace std;
    void kit()
    {
        int l = 0;
        static int s;
        ++l;
        ++s;
        cout<<l<<" "<<s<<endl;
    }
    int main()
    {
        kit();
        kit();
        kit();
    
    }
    Pls explain me this program...i am unable to get it
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    What output do you see?
    What do you find confusing about this program?

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      The int l is defined inside kit() and initialized to zero. Then it is incremented. l is now 1. Then l is displayed. Then l is destroyed when kit() completes.

      The int s is a static int. That means it is defined on the first call to kit() and initialized to 0. Like l it is incremented. s is now 1. Then s is displayed. However, s is not destroyed when kit() completes. It is still there when the next call to kit() occurs and has the value the previous call to kit() left in it.

      How this happens is left up to the compiler.

      Comment

      Working...