A troubleshooting process for a static variable application instance

Source: Internet
Author: User

# Include <stdio. h>

Void func1 (void );

Int main (void)
{
Int count;
For (COUNT = 0; count <20; count ++)
{
Printf ("at iteration % d:", count );
Func1 ();
}
Return 0;
}

Void func1 (void)
{
Static int x = 0;
Int y = 0;
Printf ("x = % d, y = % d/N", X ++, y ++ );
}

After compilation and running, the result is:
At iteration 0: x = 0, y = 0
At iteration 1: x = 1, y = 0
At iteration 2: x = 2, y = 0
At iteration 3: x = 3, y = 0
At iteration 4: x = 4, y = 0
At iteration 5: x = 5, y = 0
At iteration 6: x = 6, y = 0
At Iteration 7: x = 7, y = 0
At iteration 8: x = 8, y = 0
At iteration 9: x = 9, y = 0
At iteration 10: x = 10, y = 0
At iteration 11: x = 11, y = 0
At iteration 12: x = 12, y = 0
At iteration 13: x = 13, y = 0
At iteration 14: x = 14, y = 0
At iteration 15: x = 15, y = 0
At iteration 16: x = 16, y = 0
At iteration 17: x = 17, y = 0
At iteration 18: x = 18, y = 0
At iteration 19: x = 19, y = 0

At first I thought the results would all be x = 1, y = 1
Later, the document said that X is a static variable, so every time you execute the func1 function, X will use the value of X once, and Y will be re-initialized each time. In this case, the result should be:
X is incremented every time, but y is always equal to 1, because every time the func1 function is executed, Y is initialized to 0, and y ++ is not 1? Why is the result Y 0 each time?
**************************************** *****************************
Reply: Happyparrot (Happy parrot)
Int y = 0;
Printf ("x = % d, y = % d/N", X ++, y ++ );
-- "Y ++" means to perform this operation with y first. After the operation is completed, y will increase by 1. So it is equivalent:
Int y = 0;
Printf ("x = % d, y = % d/N", x, y );
X = x + 1;
Y = Y + 1;
You are talking about the situation of ++ y.
**************************************** *****************************

Thank you for your help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.