一个被static 修饰的变量在函数中赋值问题
时间:10-02
整理:3721RD
点击:
step被static所修饰,刚开始step可以从0->1->2这几个步骤都没有问题,执行完step = 3语句,即将退出函数(在下面1处)step 的值莫名其妙的变回2,step变量只有这个地方使用,这个是什么问题?大神们帮忙分析一下什么问题!
如下程序:
void display()
{
static u8 step = 0;
if(step == 0)
{
.
step = 1;
} else if(step == 1)
{
step = 2;
}
else if(step == 2)
{
step = 3;
}
else if(step == 3)
{
..
step = 4;
}
} -------------<1
step == 2条件下的语句是 step = 3;不是1
把display的代码贴完吧。单从这几行代码看是没有问题的,可能是其他代码的原因,所以还是贴全代码吧,包括display函数被哪里调用了也描述一下
我刚刚写了一个代码来进行测试:
- #include <stdio.h>
- 1
- 2 void display(void);
- 3
- 4 int main(int argc, char*argv[])
- 5 {
- 6 display();
- 7 display();
- 8 display();
- 9 display();
- 10 display();
- 11 display();
- 12 display();
- 13 return 0;
- 14 }
- 15
- 16
- 17 void display()
- 18 {
- 19 static int step = 0;
- 20
- 21 if(0 == step)
- 22 {
- 23 printf("when step = 0, printf step = %d\n", step);
- 24 step = 1;
- 25 printf("if step = 0 done, step = %d\n", step);
- 26 }
- 27 else if(1 == step)
- 28 {
- 29
- 30 printf("when step = 1, printf step = %d\n", step);
- 31 step = 2;
- 32 printf("if step = 1 done, step = %d\n", step);
- 33 }
- 34 else if(2 == step)
- 35 {
- 36 printf("when step = 2, printf step = %d\n", step);
- 37 step = 3;
- 38 printf("if step = 2 done, step = %d\n", step);
- 39 }
- 40 else if(3 == step)
- 41 {
- 42 printf("when step = 3, printf step = %d\n", step);
- 43 step = 4;
- 44 printf("if step = 3 done, step = %d\n", step);
- 45 }
- 46 else
- printf(" I'm here\n");
- 3 }
- 2
- 1 printf("step = %d\n",step);
- 53 }
测试结果如下:
- when step = 0, printf step = 0
- if step = 0 done, step = 1
- step = 1
- when step = 1, printf step = 1
- if step = 1 done, step = 2
- step = 2
- when step = 2, printf step = 2
- if step = 2 done, step = 3
- step = 3
- when step = 3, printf step = 3
- if step = 3 done, step = 4
- step = 4
- I'm here
- step = 4
- I'm here
- step = 4
- I'm here
- step = 4
static修饰的局部变量,可以认为他是全局变量,个人怀疑跟你的display函数的使用有关系
step==2条件里面是不是有个continue