简体   繁体   中英

Two variables in a 'for' loop in C

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?

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.

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).

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++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM