Two variables in a 'for' loop in C

為{幸葍}努か 提交于 2020-01-01 09:46:38

问题


I am writing some code where I need to use two variables in a for loop. Does the below code seem alright?

It does give me the expected result.

for (loop_1 = offset,loop_2 = (offset + 2); loop_1 >= (offset - 190),loop_2 <= (190 + offset + 2); loop_1--,loop_2++)
{
    if (  (*(uint8_t*)(in_payload + loop_1) == get_a1_byte(bitslip)) &&
         ((*(uint8_t*)(in_payload + loop_2) == get_a2_byte(bitslip)))
       )
    {
          a1_count++;
    }
}

But I am getting a compiler warning which says:

file.c:499:73: warning: left-hand operand of comma expression has no effect

What does this mean?


回答1:


The problem is the test condition:

loop_1 >= (offset - 190),loop_2 <= (190 + offset + 2)

This does not check both parts. (Well, it does, but only the result of the second part is used.)

Change it to

(loop_1 >= (offset - 190)) && (loop_2 <= (190 + offset + 2))

if you want both conditions to be checked.




回答2:


Mat is correct, but you should probably consider simplifying your code to:

for (i = 0; i <= 190; i++)
{
    uint8_t *pl1 = (uint8_t *)(in_payload + offset - i);
    uint8_t *pl2 = (uint8_t *)(in_payload + offset + i + 2);

    if (*pl1 == get_a1_byte(bitslip) && *pl2 == get_a2_byte(bitslip))
    {
        a1_count++;
    }
}

(You can obviously hoist the calculation of in_payload + offset out of the loop too, but the optimiser will almost certainly do that for you).




回答3:


For your semantically problems see caf's answer. First try to straight out your thoughts before starting to type.

One misunderstanding is that you are mixing up two different concepts of C, initialization and assignment. Obviously in your code you are thinking in the lines of an initialization where the thing with the comma would work perfectly. So the next time you encounter a similar problem, just use local variables. These are valid constructs in C99, and a good thing to use, anyhow.

You didn't give us the type of the variables but assuming size_t your for statement would look like

for (size_t loop_1 = offset, loop_2 = (offset + 2);
     loop_1 >= (offset - 190) && loop_2 <= (190 + offset + 2);
     loop_1--, loop_2++)


来源:https://stackoverflow.com/questions/7783284/two-variables-in-a-for-loop-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!