开发者

Why not incrementing z?

I am trying to write a simple state machine executor in C. I have this code:

while(1) {  
  strcpy(fsm.state[x][z], lines[i]);
  printf("%i %i\n", x, z);
  z++; i++;
  if(strcmp(lines[i], ".") == 0) x++; z = 0;
  if(strcmp(lines[i], "") == 0) break;
}

I don't understand why if z should only be reset when the current line I am reading from the lines array is equal to ".", which happens every thi开发者_如何学编程rd occurrence in my test scenario, that z stays equal to 0, even when x is successfully incremented every third line.

I need output like so:

1 0 \n 1 1 \n 1 2 \n 2 0 \n 2 1 \n 2 2 \n 3 0 \n 3 1 , etc...

Instead I get:

1 0 \n 1 0 \n 1 0 \n 2 0 \n 2 0 \n 2 0 \n 3 0 \n 3 0, etc...

What do I have to change? This might be a stupid question, but I really don't understand what's wrong here.

Thank you kindly for your help.


z is always being set to zero. The if statement doesn't work based on the line, it goes to the next semi-colon.

if(strcmp(lines[i], ".") == 0) x++; z = 0;
if(strcmp(lines[i], "") == 0) break;

Is the same as:

if(strcmp(lines[i], ".") == 0){
 x++;
}

z = 0;

if(strcmp(lines[i], "") == 0){
 break;
}

Since you have two statements (x++; z = 0;), you need to put braces around them to specify the condition:

if(strcmp(lines[i], ".") == 0){
 x++;
 z = 0;
}


use braces, avoids confusion :)

while(1) {  
  strcpy(fsm.state[x][z], lines[i]);
  printf("%i %i\n", x, z);
  z++; i++;
  if(strcmp(lines[i], ".") == 0) {
        x++; 
        z = 0;
  }
  if(strcmp(lines[i], "") == 0) {
        break;
  }
}


if(strcmp(lines[i], ".") == 0) x++; z = 0;

is the same as:

if(strcmp(lines[i], ".") == 0) 
   x++; 
z = 0;

You probably want

if(strcmp(lines[i], ".") == 0) {
     x++; 
     z = 0;
}


Your problem is in this line:

if(strcmp(lines[i], ".") == 0) x++; z = 0;

Without braces, if will only include the statement x++ and your compiler will interpret your code such like:

if(strcmp(lines[i], ".") == 0)
    x++;
z = 0;

Whereas z = 0 is executed everytime. To fix that, use braces (for 2 or more statements in an if block)

if(strcmp(lines[i], ".") == 0) {
    x++;
    z = 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜