C ++ static variables in the cocos2d-x using misunderstanding, staticcocos2d-x

Source: Internet
Author: User

C ++ static variables in the cocos2d-x using misunderstanding, staticcocos2d-x

void Cms::showMonster(CCArray*  monsterArray,int type){    <span style="color:#ff0000;">static int posN=0;</span>    for(int i=0;i<monsterArray->count();i++)   {       auto  monsterSprite=(CCSprite*)monsterArray->objectAtIndex(i);   if(type==1)        {      monsterSprite->setPosition(ccp(640+posN*480,4*32-16));     }   if(type==2)   {       monsterSprite->setPosition(ccp(160+posN*640,192*2));    }      this->addChild(monsterSprite);   posN++;   }}
In the above code, I used a static variable posN. When the game started again, I found that the location of the monster was not in the original position. This problem is caused by static variables. We know that static variables are opened in static areas of the memory space .. It has a feature that, even if the program is not finished, the variable cannot be destroyed even if it is a scenario jump .. So when we run this code again, the static variable count is not from scratch, but a value;

In C language, is static variables static and static allocated variables a concept?

Not all! For example, the global variable you defined is also the space for static allocation! Local variables are dynamically allocated in the running stack.

What is the static variable in C? Why static variables?

Static variables are global variables defined in the function scope. There are no special usage rules. They all look at your personal preferences. For global variables that only use one function, static variables are "clean ".

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.