Thread: static variable result

  1. #1
    Registered User
    Join Date
    Feb 2020
    Posts
    23

    static variable result

    Code:
    #include<stdio.h>
    
    void foo ()
    {
    	static int i = 0;
    	    printf("i = %d \n", i);
    	    i = 1;
    		printf("i = %d \n", i);	 
    	    i = 2;
    		printf("i = %d \n", i);	
    		i = 3;
    		printf("i = %d \n", i);	
    }
    int main ()
    {
    	foo ();
    	printf("\n");
    	foo ();
    	return 0;
    }
    First Call
    i = 0
    i = 1
    i = 2
    i = 3

    Second Call
    i = 3
    i = 1
    i = 2
    i = 3

    because of static keyword i become equal to 3. exactly. When code run what happen in program ?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Just remember that a static local variable retains its value after control returns to the caller. That's why the apparently initial value of i was 3 on the second call to foo.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Does this confuse you less?
    Code:
    #include<stdio.h>
    
    static int i = 0;
    
    void foo ()
    {
    	    printf("i = %d \n", i);
    	    i = 1;
    		printf("i = %d \n", i);	 
    	    i = 2;
    		printf("i = %d \n", i);	
    		i = 3;
    		printf("i = %d \n", i);	
    }
    int main ()
    {
    	foo ();
    	printf("\n");
    	foo ();
    	return 0;
    }
    The only difference here is that the variable called i now has a scope that extends to the whole file, and not just the foo() function.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Static Variable and Static method
    By codewriter in forum C++ Programming
    Replies: 6
    Last Post: 03-25-2012, 07:49 AM
  2. Replies: 8
    Last Post: 01-19-2009, 07:42 PM
  3. Static Local Variable vs. Global Variable
    By arpsmack in forum C Programming
    Replies: 7
    Last Post: 08-21-2008, 03:35 AM
  4. Replies: 6
    Last Post: 12-13-2007, 08:20 PM
  5. static class variable vs. global variable
    By nadamson6 in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2005, 03:31 PM

Tags for this Thread